﻿using BonjourQuotation.ObjectModel.ReportData;
using BonjourQuotation.ObjectModel.LoggerData;
using BonjourQuotation.UI.Models.PartialModel;
using BonjourQuotation.UI.Models.ReportModel;
using BonjourQuotation.UI.ServiceManagers;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Text;
using iTextSharp.text.pdf.parser;
using BonjourQuotation.UI.Models.Shared;
using BonjourQuotation.UI.GeneratedReport;
using BonjourQuotation.UI.Models;

namespace BonjourQuotation.UI.Controllers
{
    public class ReportController : BaseController
    {
        QuotationManager QuotaManager;
        ReportManager RepManager;
        private readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        //
        // GET: /Report/
        [Authorize]
        public ActionResult Index()
        {
            MessageBoxViewModel mes = new MessageBoxViewModel();
            mes.Message = "ok";
            return View("MessageBox", mes);
        }
        [Authorize]
        public ActionResult QuotationReport(string Id, string FreeCalc, bool Small)
        {
                QuotaManager = new QuotationManager();
                var QuotaHotelBdata = QuotaManager.LoadQuotaHotelGrid(Id);
                var QuotaLunchBdata = QuotaManager.LoadQuotaLunchDinnerGrid(Id);
                var QuotaEntranceBdata = QuotaManager.LoadQuotaEntranceGrid(Id);
                var QuotaMiscBdata = QuotaManager.LoadQuotaMiscGrid(Id);
                var QuotaBusBdata = QuotaManager.LoadQuotaBusGrid(Id);
                var QuotaGuideBdata = QuotaManager.LoadQuotaGuideGrid(Id);
                var QuotaDetailBdata = QuotaManager.GetQuotationBDataByQuotaId(Id, User.Identity.Name);
                var QuotaCostBdata = QuotaManager.LoadQuotaCostPriceGrid(Id, FreeCalc);
                List<QuotationReportHotelViewModel> hotellist = new List<QuotationReportHotelViewModel>();
                List<QuotationReportLunchDinnerViewModel> lunchlist = new List<QuotationReportLunchDinnerViewModel>();
                List<QuotationReportEntranceViewModel> entrancelist = new List<QuotationReportEntranceViewModel>();
                List<QuotationReportMiscViewModel> misclist = new List<QuotationReportMiscViewModel>();
                List<QuotationReportBusViewModel> buslist = new List<QuotationReportBusViewModel>();
                List<QuotationReportGuideViewModel> guidelist = new List<QuotationReportGuideViewModel>();
                List<QuotationReportOtherViewModel> otherlist = new List<QuotationReportOtherViewModel>();
                List<QuotationReportCostPriceViewModel> costlist = new List<QuotationReportCostPriceViewModel>();

                decimal LunchSum = 0;
                decimal LunchSumCad = 0;
                decimal DinnerSum = 0;
                decimal DinnerSumCad = 0;
                
                
                foreach (var lunch in QuotaLunchBdata.Rows)
                {
                    if (lunch.Cost > 0 && lunch.Currency != "CA")
                        LunchSum += Convert.ToDecimal(lunch.Cost);
                    if (lunch.Cost > 0 && lunch.Currency == "CA")
                        LunchSumCad += Convert.ToDecimal(lunch.Cost);
                    if (lunch.CostD > 0 && lunch.Currency != "CA")
                        DinnerSum += Convert.ToDecimal(lunch.CostD);
                    if (lunch.CostD > 0 && lunch.Currency == "CA")
                        DinnerSumCad += Convert.ToDecimal(lunch.CostD);
                        
                }

                otherlist.Add(new QuotationReportOtherViewModel {
                    CadEmpty = !QuotaCostBdata.Rows.Any(row => row.Currency == "CA"),
                    QuotaID = Id,
                    AgencyRef = QuotaDetailBdata.QuotaName,
                    EmpName = QuotaDetailBdata.Employee[Convert.ToInt32(QuotaDetailBdata.SelectedEmployeeId)],
                    BreakfastTotal = QuotaHotelBdata.BreakfSum.ToString("F") + " US" + (QuotaHotelBdata.BreakfSumCad > 0 ? QuotaHotelBdata.BreakfSumCad.ToString("F") + ", CA":""),
                    LgTotal = QuotaHotelBdata.LgSum.ToString("F") + " US" + (QuotaHotelBdata.LgSumCad > 0 ? QuotaHotelBdata.LgSumCad.ToString("F") + ", CA":""),
                    RoomPPTotal = QuotaHotelBdata.RppSum.ToString("F") + " US" + (QuotaHotelBdata.RppSumCad > 0 ? QuotaHotelBdata.RppSumCad.ToString("F") + ", CA" : ""),
                    RoomSSTotal = QuotaHotelBdata.SsSum.ToString("F") + " US" + (QuotaHotelBdata.SsSumCad > 0 ? QuotaHotelBdata.SsSumCad.ToString("F") + ", CA" : ""),
                    LunchDinnerTotal = QuotaLunchBdata.TotalSum.ToString("F") + " US" + (QuotaLunchBdata.TotalSumCad > 0 ? QuotaLunchBdata.TotalSumCad.ToString("F") + ", CA" : ""),
                    LunchTotal = LunchSum.ToString("F") + " US" + (LunchSumCad > 0 ? LunchSumCad.ToString("F") + ", CA" : ""),
                    DinnerTotal = DinnerSum.ToString("F") + " US" + (DinnerSumCad > 0 ? DinnerSumCad.ToString("F") + ", CA" : ""),
                    Confirmed = QuotaDetailBdata.Accepted,
                    DepDate = Convert.ToDateTime(QuotaDetailBdata.DepartureDate).ToString("dd/MM/yyyy"),
                    FirstQuot =Convert.ToDateTime(QuotaDetailBdata.QuotaDate).ToString("dd/MM/yyyy"),
                    ArrDate = Convert.ToDateTime(QuotaDetailBdata.ArrivalDate).ToString("dd/MM/yyyy"),
                    DinnerCount = QuotaLunchBdata.DinnerSum,
                    LunchCount = QuotaLunchBdata.LunchSum,
                    EntranceCount = QuotaEntranceBdata.PPSum,
                    PPEntranceTotal = QuotaEntranceBdata.TotalPP.ToString("F") + " US" + (QuotaEntranceBdata.TotalPPCad > 0 ? QuotaEntranceBdata.TotalPPCad.ToString("F") + ", CA" : ""),
                    PGEntranceTotal = QuotaEntranceBdata.TotalPG.ToString("F") + " US" + (QuotaEntranceBdata.TotalPGCad > 0 ? QuotaEntranceBdata.TotalPGCad.ToString("F") + ", CA" : ""),
                    PPMiscTotal = QuotaMiscBdata.TotalPP.ToString("F") + " US" + (QuotaEntranceBdata.TotalPPCad > 0 ? QuotaEntranceBdata.TotalPPCad.ToString("F") + ", CA" : ""),
                    PGMiscTotal = QuotaMiscBdata.TotalPG.ToString("F") + " US" + (QuotaEntranceBdata.TotalPGCad > 0 ? QuotaEntranceBdata.TotalPGCad.ToString("F") + ", CA" : ""),
                    EntranceGroupCount = QuotaEntranceBdata.PGSum,
                    DriverRoom = QuotaHotelBdata.DriverSum.ToString("F") + " US" + (QuotaHotelBdata.DriverSumCad > 0 ? QuotaHotelBdata.DriverSumCad.ToString("F") + ", CA" : ""),
                    BusTotal = QuotaBusBdata.TotalSum.ToString("F") + " US" + (QuotaBusBdata.TotalSumCad > 0 ? QuotaBusBdata.TotalSumCad.ToString("F") + ", CA" : ""),
                    GuideTotal = QuotaGuideBdata.TotalGuide.ToString("F") + " US" + (QuotaGuideBdata.TotalGuideCad > 0 ? QuotaGuideBdata.TotalGuideCad.ToString("F") + ", CA" : ""),
                    GuideRoom = QuotaHotelBdata.GuideSum,
                    GuideMeal = QuotaLunchBdata.GuideSum,
                    GuideEntrance = QuotaEntranceBdata.GuideSum,
                    GuideRoomCad = QuotaHotelBdata.GuideSumCad,
                    GuideMealCad = QuotaLunchBdata.GuideSumCad,
                    GuideEntranceCad = QuotaEntranceBdata.GuideSumCad,
                });
            // free calc 
                if (QuotaDetailBdata.SelectedFreeCalcType == 0)
                    otherlist[0].FreeCalcType = "No Free";
                if (QuotaDetailBdata.SelectedFreeCalcType == 1)
                    otherlist[0].FreeCalcType = "1 Pax in Dbl Free";
                if (QuotaDetailBdata.SelectedFreeCalcType == 2)
                    otherlist[0].FreeCalcType = "Single Free";
            // SSup
                if (QuotaDetailBdata.profit > 1)
                {
                    otherlist[0].SSup = QuotaHotelBdata.SsSum * Convert.ToDecimal(1 + QuotaDetailBdata.profit / 100);
                    otherlist[0].SSupCad = QuotaHotelBdata.SsSumCad * Convert.ToDecimal(1 + QuotaDetailBdata.profit / 100);
                }
                else if (QuotaDetailBdata.profit > 0 && QuotaDetailBdata.profit < 1)
                {
                    otherlist[0].SSup = QuotaHotelBdata.SsSum / Convert.ToDecimal(QuotaDetailBdata.profit);
                    otherlist[0].SSupCad = QuotaHotelBdata.SsSumCad / Convert.ToDecimal(QuotaDetailBdata.profit);
                }
            // profit
                otherlist[0].ProfitPrc = QuotaDetailBdata.profit.ToString("F");

                foreach (var hotel in QuotaHotelBdata.Rows)
                {
                    hotellist.Add(new QuotationReportHotelViewModel
                    {
                        HotelDesc = hotel.HotelDesc,
                        Luggage = hotel.Luggage,
                        Nights = hotel.Nights,
                        OccTax = hotel.OccTax,
                        Room = hotel.Room,
                        RoomPP = hotel.RoomPP,
                        SingleSupp = hotel.SingleSupp,
                        tax = Convert.ToDecimal(hotel.tax).ToString("F"),
                        BFreeFlag = hotel.BFreeFlag,
                        BGuideFlag = hotel.BGuideFlag,
                        Breakfast = hotel.Breakfast,
                        BrfType = hotel.BrfType,
                        DriverFlag = hotel.DriverFlag,
                        FreeFlag = hotel.FreeFlag,
                        GuideFlag = hotel.GuideFlag,
                        Currency = hotel.Currency == "US" ? "" : hotel.Currency == "CA"?"CA":hotel.Currency,
                    });
                }
                foreach (var lunch in QuotaLunchBdata.Rows)
                {
                    lunchlist.Add(new QuotationReportLunchDinnerViewModel
                    {
                        FreeFlag = lunch.FreeFlag,
                        GuideFlag = lunch.GuideFlag,
                        Cost = lunch.Cost,
                        CostD = lunch.CostD,
                        Day = lunch.Day,
                        Description = lunch.Description,
                        DescriptionD = lunch.DescriptionD,
                        FreeFlagD = lunch.FreeFlagD,
                        GuideFlagD = lunch.GuideFlagD,
                        Currency = lunch.Currency == "US" ? "" : lunch.Currency == "CA" ? "CA" : lunch.Currency,
                    });
                }
                foreach (var entrance in QuotaEntranceBdata.Rows)
                {
                    entrancelist.Add(new QuotationReportEntranceViewModel
                    {
                        FreeFlag = entrance.FreeFlag,
                        GuideFlag = entrance.GuideFlag,
                        Cost = entrance.Cost,
                        CostG = entrance.CostG,
                        Description = entrance.Description,
                        Currency = entrance.Currency == "US" ? "" : entrance.Currency == "CA" ? "CA" : entrance.Currency,
                    });
                }
                foreach (var misc in QuotaMiscBdata.Rows)
                {
                    misclist.Add(new QuotationReportMiscViewModel
                    {
                        Cost = misc.Cost,
                        CostG = misc.CostG,
                        Description = misc.Description,
                        Currency = misc.Currency == "US" ? "" : misc.Currency == "CA" ? "CA" : misc.Currency,
                    });
                }
                foreach (var bus in QuotaBusBdata.Rows)
                {
                    buslist.Add(new QuotationReportBusViewModel
                    {
                        Cost = bus.Cost,
                        Rate = bus.Rate,
                        Description = bus.Description,
                        Qty = bus.Qty,
                        Day = bus.Day,
                        DayNum = bus.DayQty,
                        Currency = bus.Currency == "US" ? "" : bus.Currency == "CA" ? "CA" : bus.Currency,
                    });
                }
                foreach (var guide in QuotaGuideBdata.Rows)
                {
                    guidelist.Add(new QuotationReportGuideViewModel
                    {
                        Cost = guide.Cost,
                        Rate = guide.Rate,
                        Description = guide.Description,
                        Qty = guide.Qty,
                        Day = guide.Day,
                        DayNum = guide.DayQty,
                        Currency = guide.Currency == "US" ? "" : guide.Currency == "CA" ? "CA" : guide.Currency,
                    });
                }
                foreach (var cost in QuotaCostBdata.Rows)
                {
                    costlist.Add(new QuotationReportCostPriceViewModel
                    {
                        GivenSold = cost.GivenSold,
                        Pax = cost.Pax,
                        Profit = cost.Profit,
                        PerNight = cost.GivenSold / QuotaDetailBdata.NoNights,
                        Currency = cost.Currency == "US" ? "" : cost.Currency == "CA" ? "CA" : cost.Currency,
                    });
                }
                
                LocalReport localReport = new LocalReport();
                localReport.ReportPath = Server.MapPath("~/Report/QuotationReport.rdlc");   
                if(Small)
                    localReport.ReportPath = Server.MapPath("~/Report/QuotationReportSmall.rdlc");           

                ReportDataSource reportDataSourceHotel = new ReportDataSource();
                reportDataSourceHotel.Name = "HotelDataSet";
                reportDataSourceHotel.Value = hotellist;

                ReportDataSource reportDataSourceLunch = new ReportDataSource();
                reportDataSourceLunch.Name = "LunchDinnerDataSet";
                reportDataSourceLunch.Value = lunchlist;

                ReportDataSource reportDataSourceEntrance = new ReportDataSource();
                reportDataSourceEntrance.Name = "EntranceDataSet";
                reportDataSourceEntrance.Value = entrancelist;

                ReportDataSource reportDataSourceMisc = new ReportDataSource();
                reportDataSourceMisc.Name = "MiscDataSet";
                reportDataSourceMisc.Value = misclist;

                ReportDataSource reportDataSourceBus = new ReportDataSource();
                reportDataSourceBus.Name = "BusDataSet";
                reportDataSourceBus.Value = buslist;

                ReportDataSource reportDataSourceGuide = new ReportDataSource();
                reportDataSourceGuide.Name = "GuideDataSet";
                reportDataSourceGuide.Value = guidelist;

                ReportDataSource reportDataSourceOther = new ReportDataSource();
                reportDataSourceOther.Name = "OtherDataSet";
                reportDataSourceOther.Value = otherlist;

                ReportDataSource reportDataSourceCost = new ReportDataSource();
                reportDataSourceCost.Name = "CostDataSet";
                reportDataSourceCost.Value = costlist;

                localReport.DataSources.Add(reportDataSourceHotel);
                localReport.DataSources.Add(reportDataSourceLunch);
                localReport.DataSources.Add(reportDataSourceEntrance);
                localReport.DataSources.Add(reportDataSourceMisc);
                localReport.DataSources.Add(reportDataSourceBus);
                localReport.DataSources.Add(reportDataSourceGuide);
                localReport.DataSources.Add(reportDataSourceOther);
                localReport.DataSources.Add(reportDataSourceCost);
                MessageBoxViewModel GenReportError = new MessageBoxViewModel();
                var GeneretedReport = ReportGenerator(localReport, ref GenReportError);
                if (GeneretedReport != null)
                    return File(GeneretedReport, "application/pdf");
                else
                    return View("MessageBox", GenReportError);
            
        }
        public ActionResult RoomingListReport(int GroupID, int VendorID, DateTime ArrivalDate)
        {
            
            List<RoomingListOtherInfoReportViewModel> OtherInfoList = new List<RoomingListOtherInfoReportViewModel>();
            List<RoomingListRoomInfoReportViewModel> RoomInfoList = new List<RoomingListRoomInfoReportViewModel>();
            RepManager = new ReportManager();
            var data = RepManager.RoomingListReport(GroupID, VendorID, ArrivalDate);
            int sing = 0;
            int doub = 0;
            int twin = 0;
            int triple = 0;
            int quad = 0;
            int driver = 0;
            int guide = 0;
            int pax = 0;
            int num = 0;
           
            foreach (var room in data.Rooms)
            {
                sing = room.ServiceName == "Single" ? sing + 1 : sing;
                doub = room.ServiceName == "Double" ? doub + 1 : doub;
                twin = room.ServiceName == "Twin" ? twin + 1 : twin;
                triple = room.ServiceName == "Triple" ? triple + 1 : triple;
                quad = room.ServiceName == "Quad" ? quad + 1 : quad;
                driver = room.ServiceName == "Driver" ? driver + 1 : driver;
                guide = room.ServiceName == "Guide" ? guide + 1 : guide;
                pax += room.NumOfPerson;
                num ++;
                RoomInfoList.Add(new RoomingListRoomInfoReportViewModel
                {
                    Names = room.Names,
                    Note = room.Notes,
                    Title = room.Title,
                    ServiceName = room.ServiceName,
                    Num = room.ServiceName == "Single" ? sing : room.ServiceName == "Double" ? doub : room.ServiceName == "Twin" ? twin : room.ServiceName == "Triple" ? triple : room.ServiceName == "Quad" ? quad : room.ServiceName == "Driver" ? driver : room.ServiceName == "Guide" ? guide : num,
                });
            }
            OtherInfoList.Add(new RoomingListOtherInfoReportViewModel {
                CompanyName = data.CompanyName,
                CompanyInfo = data.CompanyInfo,
                ArrivalDateTime = data.ArrivalDateTime,
                DepartureDateTime = data.DepartureDateTime,
                GroupCode = data.GroupCode,
                GroupName = data.GroupName,
                Nationality = data.Nationality,
                VendorContactNameTitle = data.VendorContactNameTitle,
                VendorFax = data.VendorFax,
                VendorName = data.VendorName,
                VendorEmail = IsEmail(data.VendorEmailSales)?data.VendorEmailSales:"",
                VendorPhoneSales = data.VendorPhoneSales,
                PorterageNotes = data.PorterageNotes,
                RoomListNotes = data.RoomListNotes + "\n" + data.RoomListEditNotes,
                IsSingle = data.Rooms.Where(room=>room.ServiceName=="Single").Count() == 0,
                IsDouble = data.Rooms.Where(room => room.ServiceName == "Double").Count() == 0,
                IsTwin = data.Rooms.Where(room => room.ServiceName == "Twin").Count() == 0,
                IsTriple = data.Rooms.Where(room => room.ServiceName == "Triple").Count() == 0,
                IsQuad = data.Rooms.Where(room => room.ServiceName == "Quad").Count() == 0,
                IsDriver = data.Rooms.Where(room => room.ServiceName == "Driver").Count() == 0,
                IsGuide = data.Rooms.Where(room => room.ServiceName == "Guide").Count() == 0,
                IsHotel = data.VendorName == null,
                RoomingListStr = pax + " PAX" + " ( " + (sing > 0 ? sing + " Single(s)" : "") + (doub > 0 ? ", "+doub + " Double(s)" : "")+
                                (twin > 0 ? ", " + twin + " Twin(s)" : "") + (triple > 0 ? ", " + triple + " Triple(s)" : "") + (quad > 0 ? ", " + quad + " Quad(s)" : "")+
                                (driver > 0 ? ", " + driver + " Driver(s)" : "") + (guide > 0 ? ", " + guide + " Guide(s)" : "") + " ) ", 
            });
            
            
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/RoomingListReport.rdlc");

            ReportDataSource reportDataSourceOtherInfo = new ReportDataSource();
            reportDataSourceOtherInfo.Name = "OtherInfoDataSet";
            reportDataSourceOtherInfo.Value = OtherInfoList;
            localReport.DataSources.Add(reportDataSourceOtherInfo);

            ReportDataSource reportDataSourceRoomInfo = new ReportDataSource();
            reportDataSourceRoomInfo.Name = "RoomInfoDataSet";
            reportDataSourceRoomInfo.Value = RoomInfoList;
            localReport.DataSources.Add(reportDataSourceRoomInfo);
            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            var GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            if (GeneretedReport != null)
                return File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);

        }
        public ActionResult MasterRoomingListReport(int GroupID)
        {

            List<RoomingListOtherInfoReportViewModel> OtherInfoList = new List<RoomingListOtherInfoReportViewModel>();
            List<RoomingListRoomInfoReportViewModel> RoomInfoList = new List<RoomingListRoomInfoReportViewModel>();
            RepManager = new ReportManager();
            var data = RepManager.MasterRoomingListReport(GroupID);
            int sing = 0;
            int doub = 0;
            int twin = 0;
            int triple = 0;
            int quad = 0;
            int driver = 0;
            int guide = 0;
            int pax = 0;
            int num = 0;
            foreach (var room in data.Rooms)
            {
                sing = room.ServiceName == "Single" ? sing + 1 : sing;
                doub = room.ServiceName == "Double" ? doub + 1 : doub;
                twin = room.ServiceName == "Twin" ? twin + 1 : twin;
                triple = room.ServiceName == "Triple" ? triple + 1 : triple;
                quad = room.ServiceName == "Quad" ? quad + 1 : quad;
                driver = room.ServiceName == "Driver" ? driver + 1 : driver;
                guide = room.ServiceName == "Guide" ? guide + 1 : guide;
                pax += room.NumOfPerson;
                num++;
                RoomInfoList.Add(new RoomingListRoomInfoReportViewModel
                {
                    Names = room.Names,
                    Note = room.Notes,
                    Title = room.Title,
                    ServiceName = room.ServiceName,
                    Num = room.ServiceName == "Single" ? sing : room.ServiceName == "Double" ? doub : room.ServiceName == "Twin" ? twin : room.ServiceName == "Triple" ? triple : room.ServiceName == "Quad" ? quad : room.ServiceName == "Driver" ? driver : room.ServiceName == "Guide" ? guide : num,
                });
            }
            OtherInfoList.Add(new RoomingListOtherInfoReportViewModel
            {
                CompanyName = data.CompanyName,
                CompanyInfo = data.CompanyInfo,
                ArrivalDateTime = data.ArrivalDateTime,
                DepartureDateTime = data.DepartureDateTime,
                GroupCode = data.GroupCode,
                GroupName = data.GroupName,
                Nationality = data.Nationality,
                IsSingle = data.Rooms.Where(room => room.ServiceName == "Single").Count() == 0,
                IsDouble = data.Rooms.Where(room => room.ServiceName == "Double").Count() == 0,
                IsTwin = data.Rooms.Where(room => room.ServiceName == "Twin").Count() == 0,
                IsTriple = data.Rooms.Where(room => room.ServiceName == "Triple").Count() == 0,
                IsQuad = data.Rooms.Where(room => room.ServiceName == "Quad").Count() == 0,
                IsDriver = data.Rooms.Where(room => room.ServiceName == "Driver").Count() == 0,
                IsGuide = data.Rooms.Where(room => room.ServiceName == "Guide").Count() == 0,
                IsHotel = data.VendorName == null,
                RoomingListStr = pax + " PAX" + " ( " + (sing > 0 ? sing + " Single(s)" : "") + (doub > 0 ? ", " + doub + " Double(s)" : "") +
                                (twin > 0 ? ", " + twin + " Twin(s)" : "") + (triple > 0 ? ", " + triple + " Triple(s)" : "") + (quad > 0 ? ", " + quad + " Quad(s)" : "") +
                                (driver > 0 ? ", " + driver + " Driver(s)" : "") + (guide > 0 ? ", " + guide + " Guide(s)" : "") + " ) ",
            });


            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/MasterRoomingListReport.rdlc");

            ReportDataSource reportDataSourceOtherInfo = new ReportDataSource();
            reportDataSourceOtherInfo.Name = "OtherInfoDataSet";
            reportDataSourceOtherInfo.Value = OtherInfoList;
            localReport.DataSources.Add(reportDataSourceOtherInfo);

            ReportDataSource reportDataSourceRoomInfo = new ReportDataSource();
            reportDataSourceRoomInfo.Name = "RoomInfoDataSet";
            reportDataSourceRoomInfo.Value = RoomInfoList;
            localReport.DataSources.Add(reportDataSourceRoomInfo);
            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            var GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            if (GeneretedReport != null)
                return File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);

        }
        public ActionResult TechProgReport(int GroupID)
        {
            List<TechProgOtherListReportViewModel> TechProgOtherList = new List<TechProgOtherListReportViewModel>();
            List<TechProgListReportViewModel> TechProgList = new List<TechProgListReportViewModel>();
            List<TechProgBusListReportViewModel> TechProgBusList = new List<TechProgBusListReportViewModel>();
            List<TechProgGuideListReportViewModel> TechProgGuideList = new List<TechProgGuideListReportViewModel>();
            RepManager = new ReportManager();
            var data = RepManager.TechProgReport(GroupID);
            TechProgOtherList.Add(new TechProgOtherListReportViewModel
            {
                CompanyName = data.CompanyName,
                CompanyInfo = data.CompanyAddress + ", " + (data.CompanyCity != null ? data.CompanyCity.ToUpper() + ", " : "") + data.CompanyState + " " + data.CompanyPostalCode,
                CompanyPhone = data.CompanyPhone,
                CompanyFax = data.CompanyFax,
                GroupInfo = data.GroupCode + " / " + data.GroupName,
                ArrivalDate = data.ArrivalDate != null ? Convert.ToDateTime(data.ArrivalDate).ToString("dd-MMM-yy").ToUpper() : "",
                DepartureDate = data.DepartureDate != null ? Convert.ToDateTime(data.DepartureDate).ToString("dd-MMM-yy").ToUpper() : "",
            });
            foreach (var brows in data.BusRows)
            {
                TechProgBusList.Add(new TechProgBusListReportViewModel
                {
                   BusName = brows.BusName,
                   Phone = FormatPhoneNumber(brows.Phone),
                   Note = brows.Notes,
                   StartDate = brows.StartDate != null ? Convert.ToDateTime(brows.StartDate).ToString("dd-MMM-yy") : null,
                   FinishDate = brows.FinishDate != null ? Convert.ToDateTime(brows.FinishDate).ToString("dd-MMM-yy") : null,
                });
            }
            foreach (var grows in data.GuideRows)
            {
                string sex = "";
                switch (grows.Sex)
                {
                    case 0:
                        sex = "Mr. ";
                        break;
                    case 1:
                        sex = "Mrs. ";
                        break;
                    case 2:
                        sex = "Ms. ";
                        break;
                    default:
                        break;
                }
                TechProgGuideList.Add(new TechProgGuideListReportViewModel
                {
                    GuideInfo = sex + grows.FirstName + " " + grows.LastName,
                    Phone = FormatPhoneNumber(grows.Phone),
                    Note = grows.Notes,
                    StartDate = grows.StartDate != null ? Convert.ToDateTime(grows.StartDate).ToString("dd-MMM-yy") : null,
                    FinishDate = grows.FinishDate != null ? Convert.ToDateTime(grows.FinishDate).ToString("dd-MMM-yy") : null,
                });
            }
            var CurrentDate = (DateTime?)null;
            string Area = "";
            string Via = "";
            foreach (var rows in data.Rows)
            {
                if(CurrentDate != rows.Date)
                {
                    CurrentDate = rows.Date;
                    if (data.Rows.Any(row => row.Date == CurrentDate && row.Type == "Hotel"))
                    {
                        Area = data.Rows.Where(row => row.Date == CurrentDate && row.Type == "Hotel").FirstOrDefault().Area;
                        Via = data.Rows.Where(row => row.Date == CurrentDate && row.Type == "Hotel").FirstOrDefault().Via;
                    }
                    else
                    {
                        Area = "";
                        Via = "";
                    }
                }
                string sex = "";
                switch (rows.Sex)
                {
                    case 0:
                        sex = "Mr. ";
                        break;
                    case 1:
                        sex = "Mrs. ";
                        break;
                    case 2:
                        sex = "Ms. ";
                        break;
                    default:
                        break;
                }
                TechProgList.Add(new TechProgListReportViewModel
                {
                    Description = rows.Description,
                    Area = Area,
                    Day = data.ArrivalDate != null ? Convert.ToInt32((Convert.ToDateTime(rows.Date) - Convert.ToDateTime(data.ArrivalDate)).TotalDays) + 1 : 0,
                    Date = rows.Date.ToString("dddd, MMMM dd, yyyy") + "   " + Via,
                    Time = rows.Type != "Hotel" ?  new DateTime().Add(rows.Time).ToString("hh:mm tt") : "",
                    PhoneNumber = (rows.DetailID == null || rows.DetailID == 0
                                   || (rows.Type != "Hotel" && rows.Type != "Restaurant")
                                   || rows.VendorID == null) ? "" : FormatPhoneNumber(rows.VendorPhone),
                    VendorGuideInfo = rows.DetailDescription + (rows.VendorID != null ?
                                      (rows.VendorName != null ? " / " + rows.VendorName.ToUpper() + " " + ((rows.Type != "Hotel" && rows.Type != "Restaurant") ? ""
                                      : (rows.VendorAddress != null ? rows.VendorAddress.ToUpper() + ", " : "") + (rows.VendorCity != null ? rows.VendorCity.ToUpper() + ", " : "") + (rows.VendorState != null ? rows.VendorState.ToUpper() : "")) : "")
                                      + (rows.GuideID != null ? " /Guide: " + sex + rows.FirstName + " " + rows.LastName: "" ) : ""),
                });
            }
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/TechProgReport.rdlc");

            ReportDataSource reportDataSourceTechProgOtherList = new ReportDataSource();
            reportDataSourceTechProgOtherList.Name = "TechProgOtherListDataSet";
            reportDataSourceTechProgOtherList.Value = TechProgOtherList;
            localReport.DataSources.Add(reportDataSourceTechProgOtherList);

            ReportDataSource reportDataSourceTechProgList = new ReportDataSource();
            reportDataSourceTechProgList.Name = "TechProgListDataSet";
            reportDataSourceTechProgList.Value = TechProgList;
            localReport.DataSources.Add(reportDataSourceTechProgList);

            ReportDataSource reportDataSourceTechProgBusList = new ReportDataSource();
            reportDataSourceTechProgBusList.Name = "TechProgBusListDataSet";
            reportDataSourceTechProgBusList.Value = TechProgBusList;
            localReport.DataSources.Add(reportDataSourceTechProgBusList);

            ReportDataSource reportDataSourceTechProgGuideList = new ReportDataSource();
            reportDataSourceTechProgGuideList.Name = "TechProgGuideListDataSet";
            reportDataSourceTechProgGuideList.Value = TechProgGuideList;
            localReport.DataSources.Add(reportDataSourceTechProgGuideList);
            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            var GeneretedReport = ReportGenerator(localReport, ref GenReportError);

            if (GeneretedReport != null)
                return File(GeneretedReport, "application/pdf");
                //return File(GeneretedReport, "application/vnd.ms-excel");
            else
                return View("MessageBox", GenReportError);

        }
        public ActionResult GroupVendorListReport(int GroupID)
        {

            List<GVendorListOtherInfoReportViewModel> OtherInfoList = new List<GVendorListOtherInfoReportViewModel>();
            List<GVendorListHotelReportViewModel> HotelInfoList = new List<GVendorListHotelReportViewModel>();
            RepManager = new ReportManager();
            var data = RepManager.GroupVendorListReport(GroupID);
            
            foreach (var hotel in data.Hotels)
            {
                var DepDate = hotel.DepartureDate != null ? Convert.ToDateTime(hotel.DepartureDate).ToString("ddd, dd/MMM/yy") : "";
                HotelInfoList.Add(new GVendorListHotelReportViewModel
                {
                    HotelName = hotel.HotelName,
                    HotelCity = hotel.HotelCity,
                    HotelAddress = hotel.HotelAddress,
                    ArrDepDates = hotel.ArrivalDate.ToString("ddd, dd/MMM/yy") + " - " + DepDate,
                    HotelFax = (hotel.HotelFax != null && hotel.HotelFax.Length == 10) ? String.Format("Fax: ({0}) {1}-{2}", hotel.HotelFax.Substring(0, 3), hotel.HotelFax.Substring(3, 3), hotel.HotelFax.Substring(6, 4)) : "Fax: " + hotel.HotelFax,
                    HotelPhone = (hotel.HotelPhone != null && hotel.HotelPhone.Length == 10) ? String.Format("Phone: ({0}) {1}-{2}", hotel.HotelPhone.Substring(0, 3), hotel.HotelPhone.Substring(3, 3), hotel.HotelPhone.Substring(6, 4)) : "Phone: " + hotel.HotelPhone,
                });
            }
            OtherInfoList.Add(new GVendorListOtherInfoReportViewModel
            {
                CompanyName = data.CompanyName,
                CompanyInfo = data.CompanyInfo,
                ArrivalDepartureDate = Convert.ToDateTime(data.ArrivalDate).ToString("ddd, dd/MMM/yy") + " - " + Convert.ToDateTime(data.DepartureDate).ToString("ddd, dd/MMM/yy"),
                GroupID = data.GroupID,
                GroupName = data.GroupName,
                Customer = data.Customer,
                CustomerContactName = data.CustomerContactName,
                CustomerPhone = (data.CustomerPhone != null && data.CustomerPhone.Length == 10) ? String.Format("({0}) {1}-{2}", data.CustomerPhone.Substring(0, 3), data.CustomerPhone.Substring(3, 3), data.CustomerPhone.Substring(6, 4)) : data.CustomerPhone,
                CustomerFax = (data.CustomerFax != null && data.CustomerFax.Length == 10) ? String.Format("({0}) {1}-{2}", data.CustomerFax.Substring(0, 3), data.CustomerFax.Substring(3, 3), data.CustomerFax.Substring(6, 4)) : data.CustomerFax,
                CustomerEmail = data.CustomerEmail,
                RoomCount = data.RoomCount != null? data.RoomCount.ToString():"",
                EmpName = data.EmpName,
            });


            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/GVendorListReport.rdlc");

            ReportDataSource reportDataSourceOtherInfo = new ReportDataSource();
            reportDataSourceOtherInfo.Name = "VendorOtherInfoDataSet";
            reportDataSourceOtherInfo.Value = OtherInfoList;
            localReport.DataSources.Add(reportDataSourceOtherInfo);

            ReportDataSource reportDataSourceHotelInfo = new ReportDataSource();
            reportDataSourceHotelInfo.Name = "VendorListHotelDataSet";
            reportDataSourceHotelInfo.Value = HotelInfoList;
            localReport.DataSources.Add(reportDataSourceHotelInfo);
            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            var GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            if (GeneretedReport != null)
                return File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);

        }
        public ActionResult GroupInvoiceReport(int GroupID)
        {
            List<GroupInvoiceOtherReportViewModel> InvOtherList = new List<GroupInvoiceOtherReportViewModel>();
            List<GroupInvoiceReportViewModel> InvList = new List<GroupInvoiceReportViewModel>();
            RepManager = new ReportManager();
            var data = RepManager.GroupInvoiceReport(GroupID);

            foreach (var inv in data.Invoices)
            {
                InvList.Add(new GroupInvoiceReportViewModel
                {
                    Qty = inv.Qty.ToString(),
                    Description = inv.Description,
                    Price = DoubleStringGeneratorF((double?)inv.Price),
                    Credit = DoubleStringGeneratorF((double?)inv.Credit),
                    Debit = DoubleStringGeneratorF((double?)inv.Debit),
                    Curr = inv.Curr,
                });
            }
            var TotalCrd = data.Invoices.Sum(crd => crd.Credit);
            var TotalDeb = data.Invoices.Sum(crd => crd.Debit);
            InvOtherList.Add(new GroupInvoiceOtherReportViewModel
            {
                CompanyName = data.CompanyName,
                CompanyAddress = data.CompanyAddress,
                CompanyPhone = "Phone: " + data.CompanyPhone + " Fax: " + data.CompanyFax,
                CompanyFedID = "Federal ID: " + data.CompanyFedID,
                InvoiceNo = data.InvoiceNo,
                InvoiceDate = data.InvoiceDate != null ? Convert.ToDateTime(data.InvoiceDate).ToString("dd/MMM/yy"):"",
                GroupName = data.GroupName,
                ArrivalDate = data.ArrivalDate != null ? Convert.ToDateTime(data.ArrivalDate).ToString("dd/MMM/yy") : "",
                PaymentDueDate = data.PaymentDueDate != null ? Convert.ToDateTime(data.PaymentDueDate).ToString("dd/MMM/yy") : "",
                FinalPayment = data.FinalPayment != null ? Convert.ToDateTime(data.FinalPayment).ToString("dd/MMM/yy") : "",
                PaymentTerms = data.PaymTerms,
                AgentName = data.AgentName,
                Customer = data.Customer + (data.Contact != null ? " Attn: " + data.Contact : ""),
                CustomerAddress = data.CustomerAddress,
                ContactData = data.Contact == null ? "" : ("" + (data.ContactTitle == null ? "" : " Title: " + data.ContactTitle) + (data.ContactPhone == null ? (data.ContactFax == null ? "" : "") : ((" \n Phone: " + data.ContactPhone) + (data.ContactFax == null ? "" : ""))) + (data.ContactEmail == null ? "" : "")),
                InvComments = data.InvComm,
                ProInvComments = data.ProInvComm,
                DepositAmt = data.DepositM == true ? DoubleStringGeneratorF((double?)data.DepositAmt) : DoubleStringGeneratorF((double?)((Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)) * (decimal)0.2)),
                FinalDepositAmt = data.DepositM == true ? DoubleStringGeneratorF((double?)((Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)) - data.DepositAmt)) : DoubleStringGeneratorF((double?)((Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)) - ((Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)) * (decimal)0.2))),
                TotalDebit = DoubleStringGeneratorF((double?)TotalDeb),
                TotalCredit = DoubleStringGeneratorF((double?)TotalCrd),
                AmountDue = data.ProInv == true ? Convert.ToDecimal(Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd) - Convert.ToDecimal(data.InvTotalDeposit)) : Convert.ToDecimal(Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)),
                Deposit = data.ProInv == true ? DoubleStringGeneratorF((double?)data.InvTotalDeposit) : DoubleStringGeneratorF((double?)(Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd))),
                Credit = DoubleStringGeneratorF((double?)(TotalDeb - TotalCrd - data.InvTotalDeposit)),
                PayAddress = data.PayBankName + ", " + data.PayAddress,
                PayAccountInfo = "Acc Nr.:" + data.PayAccNo + "  " + "ABA Nr.:" + data.PayAbaNo + "   " + "Swift Code:" + data.PaySwiftCode,
            });
            

            LocalReport localReport = new LocalReport();
            if (data.ProInv == true)
            {
                localReport.ReportPath = Server.MapPath("~/Report/GroupInvoiceReport.rdlc");
            }
            else
            {
                localReport.ReportPath = Server.MapPath("~/Report/GroupProInvoiceReport.rdlc");
            }

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "GroupInvoiceOtherDataSet";
            reportDataSourceOther.Value = InvOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceInvoice = new ReportDataSource();
            reportDataSourceInvoice.Name = "GroupInvoiceListDataSet";
            reportDataSourceInvoice.Value = InvList;
            localReport.DataSources.Add(reportDataSourceInvoice);
            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            var GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            if (GeneretedReport != null)
                return File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);

        }
        public ActionResult GirGroupInvoiceReport(int GroupID, int CustomerID)
        {
            List<GroupInvoiceOtherReportViewModel> InvOtherList = new List<GroupInvoiceOtherReportViewModel>();
            List<GroupInvoiceReportViewModel> InvList = new List<GroupInvoiceReportViewModel>();
            RepManager = new ReportManager();
            var data = RepManager.GirGroupInvoiceReport(GroupID, CustomerID);

            foreach (var inv in data.Invoices)
            {
                InvList.Add(new GroupInvoiceReportViewModel
                {
                    Qty = inv.Qty.ToString(),
                    Description = inv.Description,
                    Price = inv.Price != null ? Convert.ToDecimal(inv.Price).ToString("F") : "",
                    Credit = inv.Credit != null ? Convert.ToDecimal(inv.Credit).ToString("F") : "",
                    Debit = inv.Debit != null ? Convert.ToDecimal(inv.Debit).ToString("F") : "",
                    Curr = inv.Curr,
                });
            }
            var TotalCrd = data.Invoices.Sum(crd => crd.Credit);
            var TotalDeb = data.Invoices.Sum(crd => crd.Debit);
            InvOtherList.Add(new GroupInvoiceOtherReportViewModel
            {
                CompanyName = data.CompanyName,
                CompanyAddress = data.CompanyAddress,
                CompanyPhone = "Phone: " + data.CompanyPhone + " Fax: " + data.CompanyFax,
                CompanyFedID = "Federal ID: " + data.CompanyFedID,
                InvoiceNo = data.InvoiceNo,
                InvoiceDate = data.InvoiceDate != null ? Convert.ToDateTime(data.InvoiceDate).ToString("dd/MMM/yy") : "",
                GroupName = data.GroupName,
                ArrivalDate = data.ArrivalDate != null ? Convert.ToDateTime(data.ArrivalDate).ToString("dd/MMM/yy") : "",
                PaymentDueDate = data.PaymentDueDate != null ? Convert.ToDateTime(data.PaymentDueDate).ToString("dd/MMM/yy") : "",
                FinalPayment = data.FinalPayment != null ? Convert.ToDateTime(data.FinalPayment).ToString("dd/MMM/yy") : "",
                PaymentTerms = data.PaymTerms,
                AgentName = data.AgentName,
                Customer = data.Customer + (data.Contact != null ? " Attn: " + data.Contact : ""),
                CustomerAddress = data.CustomerAddress,  
                ContactData = data.Contact == null ? "" : ("" + (data.ContactTitle == null ? "" : " Title: " + data.ContactTitle) + (data.ContactPhone == null ? (data.ContactFax == null ? "" : "") : ((" \n Phone: " + data.ContactPhone) + (data.ContactFax == null ? "" : ""))) + (data.ContactEmail == null ? "" : "")),
                InvComments = data.InvComm,
                ProInvComments = data.ProInvComm,
                DepositAmt = data.DepositM == true ? DoubleStringGeneratorF((double?)data.DepositAmt) : DoubleStringGeneratorF((double?)((Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)) * (decimal)0.2)),
                FinalDepositAmt = data.DepositM == true ? DoubleStringGeneratorF((double?)((Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)) - data.DepositAmt)) : DoubleStringGeneratorF((double?)((Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)) - ((Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)) * (decimal)0.2))),
                TotalDebit = DoubleStringGeneratorF((double?)TotalDeb),
                TotalCredit = DoubleStringGeneratorF((double?)TotalCrd),
                AmountDue = data.ProInv == true ? Convert.ToDecimal(Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd) - Convert.ToDecimal(data.InvTotalDeposit)) : Convert.ToDecimal(Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd)),
                Deposit = data.ProInv == true ? DoubleStringGeneratorF((double?)data.InvTotalDeposit) : DoubleStringGeneratorF((double?)(Convert.ToDecimal(TotalDeb) - Convert.ToDecimal(TotalCrd))),
                Credit = DoubleStringGeneratorF((double?)(TotalDeb - TotalCrd - data.InvTotalDeposit)),
                PayAddress = data.PayBankName + ", " + data.PayAddress,
                PayAccountInfo = "Acc Nr.:" + data.PayAccNo + "  " + "ABA Nr.:" + data.PayAbaNo + "   " + "Swift Code:" + data.PaySwiftCode,
            });


            LocalReport localReport = new LocalReport();

            if (data.ProInv == true)
            {
                localReport.ReportPath = Server.MapPath("~/Report/GroupInvoiceReport.rdlc");
            }
            else
            {
                localReport.ReportPath = Server.MapPath("~/Report/GroupProInvoiceReport.rdlc");
            }

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "GroupInvoiceOtherDataSet";
            reportDataSourceOther.Value = InvOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceInvoice = new ReportDataSource();
            reportDataSourceInvoice.Name = "GroupInvoiceListDataSet";
            reportDataSourceInvoice.Value = InvList;
            localReport.DataSources.Add(reportDataSourceInvoice);
            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            var GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            if (GeneretedReport != null)
                return File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);

        }
        [HttpGet]
        public ActionResult FrmCountryCustomerGroupRevenueReport()
        {
            FrmCountryCustomerGroupRevenueReportViewModel Vmodel = new FrmCountryCustomerGroupRevenueReportViewModel();
            RepManager = new ReportManager();
            var data = RepManager.LoadFrmCountryCustomerGroupRevenueReport();
            Vmodel.Nationalities = new List<System.Web.WebPages.Html.SelectListItem>();
            Vmodel.SelectedNationalityID = null;
            foreach (var nationality in data.Nationalities)
                Vmodel.Nationalities.Add(new System.Web.WebPages.Html.SelectListItem() { Text = nationality.Value, Value = nationality.Key.ToString() });
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmCountryCustomerGroupRevenueReport", Vmodel);
        }
        [HttpPost]
        public ActionResult CountryCustomerGroupRevenueReport(FrmCountryCustomerGroupRevenueReportViewModel model)
        {

            List<CountryCustomerGroupRevenueOtherReportViewModel> InvOtherList = new List<CountryCustomerGroupRevenueOtherReportViewModel>();
            List<CountryCustomerGroupRevenueReportViewModel> InvList = new List<CountryCustomerGroupRevenueReportViewModel>();
            RepManager = new ReportManager();
            CountryCustomerGroupRevenueReportBData data = RepManager.CountryCustomerGroupRevenueReport(model.SelectedNationalityID != null ? Convert.ToInt32(model.SelectedNationalityID) : 0, Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate));
            InvOtherList.Add(new CountryCustomerGroupRevenueOtherReportViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                Nationality = data.Nationality + " Group Totals by Customer ",
                BalanceSum = DoubleStringGenerator((double?)(from rev in data.Revenues
                              select Convert.ToDouble(rev.Balance)).Sum()),
                TotalInvoiceSum = DoubleStringGenerator((double?)(from rev in data.Revenues
                                   select Convert.ToDouble(rev.TotalInvoice)).Sum()),
                TotalPaidSum = DoubleStringGenerator((double?)(from rev in data.Revenues
                                select Convert.ToDouble(rev.TotalPaid)).Sum()),
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
                TotalNumberOfGroups = data.Revenues.Count.ToString(),
            });
            foreach (var rev in data.Revenues)
            {
                InvList.Add(new CountryCustomerGroupRevenueReportViewModel
                {
                    GroupID = rev.GroupID.ToString(),
                    CustomerCode = rev.Customer,
                    OrganizationName = rev.CustomerName,
                    Balance = DoubleStringGenerator((double?)rev.Balance),
                    TotalInvoice = DoubleStringGenerator((double?)rev.TotalInvoice),
                    TotalPaid = DoubleStringGenerator((double?)rev.TotalPaid),
                });
            }

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/CountryCustomerGroupRevenueReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "CustomerGroupRevenueOtherDataSet";
            reportDataSourceOther.Value = InvOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "CustomerGroupRevenueListDataSet";
            reportDataSourceList.Value = InvList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["CountryCustomerGroupRevenueReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CountryCustomerGroupRevenueReportOpen()
        {
            var Res = Session["CountryCustomerGroupRevenueReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmCustomerInvoiceReport()
        {
            FrmCustomerInvoiceReportViewModel Vmodel = new FrmCustomerInvoiceReportViewModel();
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmCustomerInvoiceReport", Vmodel);
        }
        [HttpPost]
        public ActionResult CustomerInvoiceSummaryReport(FrmCustomerInvoiceReportViewModel model)
        {

            List<CustomerInvoiceOtherReportViewModel> InvOtherList = new List<CustomerInvoiceOtherReportViewModel>();
            List<CustomerInvoiceReportViewModel> InvList = new List<CustomerInvoiceReportViewModel>();
            RepManager = new ReportManager();
            CustomerInvoiceReportBData data = RepManager.CustomerInvoiceReport(model.SelectedCustomerID != null ? Convert.ToInt32(model.SelectedCustomerID) : 0, Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate));
            InvOtherList.Add(new CustomerInvoiceOtherReportViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                Customer = data.CustomerDetail.CustomerCode + "   " + data.CustomerDetail.OrganizationName,
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
                TotalNumberOfGroups = data.Invoices.Count.ToString(),
                TotalNumberOfGroupsCustomer = "$" + data.Invoices.Count.ToString(),
                BalanceSum = DoubleStringGenerator((double?)(from invoice in data.Invoices
                              select Convert.ToDouble(invoice.Balance)).Sum()),
                TotalInvoiceSum = DoubleStringGenerator((double?)(from invoice in data.Invoices
                                   select Convert.ToDouble(invoice.TotalInvoice)).Sum()),
                DepositSum = DoubleStringGenerator((double?)((from invoice in data.Invoices
                              select Convert.ToDouble(invoice.Deposit)).Sum())),
                TotalPaidSum = DoubleStringGenerator((double?)(from invoice in data.Invoices
                                select Convert.ToDouble(invoice.TotalPaid)).Sum()),
                BalanceSum_0_30_ = (from invoice in data.Invoices
                                    where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) > 0
                                    && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) <= 30
                                    select Convert.ToDouble(invoice.Balance)).Any() ? DoubleStringGenerator((double?)(from invoice in data.Invoices
                                    where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) > 0
                                    && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) <= 30
                                    select Convert.ToDouble(invoice.Balance)).Sum()) : "",
                BalanceSum_30_60_ = (from invoice in data.Invoices
                                     where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) > 30
                                     && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) <= 60
                                     select Convert.ToDouble(invoice.Balance)).Any() ? DoubleStringGenerator((double?)(from invoice in data.Invoices
                                     where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) > 30
                                     && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) <= 60
                                     select Convert.ToDouble(invoice.Balance)).Sum()) : "",
                BalanceSum_60_90_ = (from invoice in data.Invoices
                                     where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) > 60
                                     && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) <= 90
                                     select Convert.ToDouble(invoice.Balance)).Any() ? DoubleStringGenerator((double?)(from invoice in data.Invoices
                                     where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) > 60
                                     && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) <= 90
                                     select Convert.ToDouble(invoice.Balance)).Sum()) : "",
                BalanceSum_90_ = (from invoice in data.Invoices
                                  where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) > 90
                                  select Convert.ToDouble(invoice.Balance)).Any() ? DoubleStringGenerator((double?)(from invoice in data.Invoices
                                  where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(invoice.FinalDue.Value.ToString())).TotalDays) > 90
                                  select Convert.ToDouble(invoice.Balance)).Sum()) : "",
            });
            foreach (var inv in data.Invoices)
            {
                InvList.Add(new CustomerInvoiceReportViewModel
                {
                    GroupCode = inv.GroupCode,
                    GroupName = inv.GroupName,
                    ArrivalDate = inv.ArrivalDate != null ? Convert.ToDateTime(inv.ArrivalDate).ToString("dd-MMM-yy") : "",
                    DepositDue = inv.DepositDue != null ? Convert.ToDateTime(inv.DepositDue).ToString("dd-MMM-yy") : "",
                    FinalDue = inv.FinalDue != null ? Convert.ToDateTime(inv.FinalDue).ToString("dd-MMM-yy") : "",
                    Balance = DoubleStringGenerator((double?)inv.Balance),
                    TotalInvoice = DoubleStringGenerator((double?)inv.TotalInvoice),
                    Deposit = DoubleStringGenerator((double?)inv.Deposit),
                    TotalPaid = DoubleStringGenerator((double?)inv.TotalPaid),
                });
            }

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/CustomerInvoiceSummaryReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "CustomerInvoiceOtherDataSet";
            reportDataSourceOther.Value = InvOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "CustomerInvoiceListDataSet";
            reportDataSourceList.Value = InvList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["CustomerInvoiceSummaryReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CustomerInvoiceSummaryReportOpen()
        {
            var Res = Session["CustomerInvoiceSummaryReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmCustomerPaymentReport()
        {
            FrmCustomerPaymentReportViewModel Vmodel = new FrmCustomerPaymentReportViewModel();
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmCustomerPaymentReport", Vmodel);
        }
        [HttpPost]
        public ActionResult CustomerPaymentReport(FrmCustomerPaymentReportViewModel model)
        {

            List<CustomerPaymentOtherReportViewModel> PayOtherList = new List<CustomerPaymentOtherReportViewModel>();
            List<CustomerPaymentReportViewModel> PayList = new List<CustomerPaymentReportViewModel>();
            RepManager = new ReportManager();
            CustomerPaymentReportBData data = RepManager.CustomerPaymentReport(model.SelectedCustomerID != null ? Convert.ToInt32(model.SelectedCustomerID) : 0, Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate));
            PayOtherList.Add(new CustomerPaymentOtherReportViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                Customer = data.CustomerPaymentDetail.CustomerCode + "   " + data.CustomerPaymentDetail.OrganizationName,
                ReportTotal = DoubleStringGenerator((double?)data.Payments.Select(ptype => ptype.Rows.Select(row => row.Balance).Sum()).Sum()),
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            });
            foreach (var pay in data.Payments)
            {
                if (pay.Rows.Count==0)
                {
                    PayList.Add(new CustomerPaymentReportViewModel
                    {
                        LineNo = pay.LineNo != null ? Convert.ToInt32(pay.LineNo) : 0,
                        Description = pay.Description,
                        PayTypeCode = pay.PayTypeCode,
                        PaymentDate = pay.PaymentDate != null ? Convert.ToDateTime(pay.PaymentDate).ToString("dd-MMM-yy") : "",
                        Payment = DoubleStringGenerator((double?)pay.Payment),
                        Refunded = pay.Refunded != null ? DoubleStringGenerator((double?)pay.Refunded) : "",
                        GroupCode = "",
                        GroupName = "",
                        Balance = "$0",
                    });
                }
                else
                    foreach (var payrow in pay.Rows)
                    {
                        PayList.Add(new CustomerPaymentReportViewModel
                        {
                            LineNo = pay.LineNo != null ? Convert.ToInt32(pay.LineNo) : 0,
                            Description = pay.Description,
                            PayTypeCode = pay.PayTypeCode,
                            PaymentDate = pay.PaymentDate != null ? Convert.ToDateTime(pay.PaymentDate).ToString("dd-MMM-yy") : "",
                            Refunded = pay.Refunded != null ? DoubleStringGenerator((double?)pay.Refunded) : "",
                            Payment = DoubleStringGenerator((double?)pay.Payment),
                            GroupCode = payrow.GroupCode,
                            GroupName = payrow.GroupName,
                            Balance = DoubleStringGenerator((double?)payrow.Balance),
                        });
                    }
            }

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/CustomerPaymentReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "CustomerPaymentOtherDataSet";
            reportDataSourceOther.Value = PayOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "CustomerPaymentListDataSet";
            reportDataSourceList.Value = PayList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["CustomerPaymentReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CustomerPaymentReportOpen()
        {
            var Res = Session["CustomerPaymentReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmCustomerGroupReport()
        {
            FrmCustomerGroupReportViewModel Vmodel = new FrmCustomerGroupReportViewModel();
            Dictionary<bool, string> IsGir = new Dictionary<bool, string>() { { true, "Yes" }, { false, "No" } };
            Vmodel.IsGir = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var element in IsGir)
            {
                Vmodel.IsGir.Add(new System.Web.WebPages.Html.SelectListItem() { Text = element.Value, Value = element.Key.ToString() });
            }
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmCustomerGroupReport", Vmodel);
        }
        [HttpPost]
        public ActionResult CustomerGroupReport(FrmCustomerGroupReportViewModel model)
        {
            List<CustomerGroupReportOtherViewModel> CustomerGroupOtherList = new List<CustomerGroupReportOtherViewModel>();
            List<CustomerGroupReportViewModel> CustomerGroupList = new List<CustomerGroupReportViewModel>();
            RepManager = new ReportManager();
            CustomerGroupReportBData data = RepManager.CustomerGroupReport(model.SelectedCustomerID != null ? Convert.ToInt32(model.SelectedCustomerID) : 0, Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate), model.SelectedIsGir);
           
            int PersonSum = 0;
            foreach (var grp in data.Groups)
            {
                CustomerGroupList.Add(new CustomerGroupReportViewModel
                {
                    GroupCode = grp.GroupCode,
                    GroupName = grp.GroupName,
                    ArrivalDate = grp.ArrivalDate != null ? Convert.ToDateTime(grp.ArrivalDate).ToString("dd-MMM-yy") : "",
                    DepartureDate = grp.DepartureDate != null ? Convert.ToDateTime(grp.DepartureDate).ToString("dd-MMM-yy") : "",
                    ArrivalCity = grp.ArrivalCity,
                    DepartureCity = grp.DepartureCity,
                    NoOfPerson = grp.NoOfPerson.ToString(),
                    IsGir = grp.IsGir == true ? "Yes" : "No",
                });
                PersonSum = PersonSum + (grp.NoOfPerson != null ? Convert.ToInt32(grp.NoOfPerson) : 0);
            }
            CustomerGroupOtherList.Add(new CustomerGroupReportOtherViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                Customer = data.CustomerDetail.CustomerCode + "   " + data.CustomerDetail.OrganizationName,
                CustomerTotal = data.Groups.Count > 1 ?
                data.Groups.Count.ToString() + " [" + data.CustomerDetail.CustomerCode + "] groups between " + Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                : data.Groups.Count.ToString() + " [" + data.CustomerDetail.CustomerCode + "] group between " + Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy"),
                ReportTotal = data.Groups.Count > 1 ?
                "Total " + data.Groups.Count.ToString() + " groups between " + Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                : "Total " + data.Groups.Count.ToString() + " group between " + Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy"),
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
                NoOfPersonSum = PersonSum.ToString(),
            });
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/CustomerGroupReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "CustomerGroupOtherDataSet";
            reportDataSourceOther.Value = CustomerGroupOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "CustomerGroupListDataSet";
            reportDataSourceList.Value = CustomerGroupList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["CustomerGroupReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CustomerGroupReportOpen()
        {
            var Res = Session["CustomerGroupReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmVendorGroupReport()
        {
            FrmVendorGroupReportViewModel Vmodel = new FrmVendorGroupReportViewModel();
            RepManager = new ReportManager();
            var Data = RepManager.LoadFrmVCnfStatus();
            Vmodel.Plane = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var plane in VndGrpRepData.Plane)
                Vmodel.Plane.Add(new System.Web.WebPages.Html.SelectListItem() { Text = plane.Value, Value = plane.Key.ToString() });
            Vmodel.Category = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var type in VndGrpRepData.Category)
                Vmodel.Category.Add(new System.Web.WebPages.Html.SelectListItem() { Text = type.Key, Value = type.Key });
            Vmodel.PaperFormats = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var type in VndGrpRepData.PaperProprties)
                Vmodel.PaperFormats.Add(new System.Web.WebPages.Html.SelectListItem() { Text = type.Key, Value = type.Key });
            Vmodel.Tabs = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var tab in VndGrpRepData.TabColumns)
                Vmodel.Tabs.Add(new System.Web.WebPages.Html.SelectListItem() { Text = tab.Key, Value = tab.Key });
            Vmodel.SelectedTab = "Hotel";
            Vmodel.TabColumns = new List<CheckBoxControlViewModel>();
            foreach (var TabColumn in VndGrpRepData.TabColumns["Hotel"])
                Vmodel.TabColumns.Add(new CheckBoxControlViewModel() { Id = TabColumn.Key, Name = TabColumn.Value.ColumnName });
            Vmodel.Status = new List<CheckBoxControlViewModel>();
            foreach (var status in Data.Status)
                Vmodel.Status.Add(new CheckBoxControlViewModel() { Id = status.Key.ToString(), Name = status.Value });
            Vmodel.CityDrop = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var city in Data.City)
                Vmodel.CityDrop.Add(new System.Web.WebPages.Html.SelectListItem() { Text = city.Value, Value = city.Key.ToString() });
            Dictionary<bool, string> IsGir = new Dictionary<bool, string>() { { true, "Yes" }, { false, "No" } };
            Vmodel.IsGir = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var element in IsGir)
            {
                Vmodel.IsGir.Add(new System.Web.WebPages.Html.SelectListItem() { Text = element.Value, Value = element.Key.ToString() });
            }
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmVendorGroupReport", Vmodel);
        }
        [HttpPost]
        public ActionResult VendorGroupReport(FrmVendorGroupReportViewModel model)
        {
            VendorGroupReportOtherViewModel VendorGroupOther = new VendorGroupReportOtherViewModel();
            List<VendorGroupReportViewModel> VendorGroupList = new List<VendorGroupReportViewModel>();
            RepManager = new ReportManager();
            VendorGroupReportBData data = RepManager.VendorGroupReport(model.SelectedVendorID != null ? Convert.ToInt32(model.SelectedVendorID) : 0, Convert.ToDateTime(model.Lower), Convert.ToDateTime(model.Upper), model.SelectedTab, model.SelectedStatus, model.ReportCitySearch, model.SelectedPlane != null ? Convert.ToBoolean(model.SelectedPlane) : (bool?)null, model.SelectedCategory, model.SelectedCityText, model.SelectedIsGir);

            foreach (var grp in data.VenGroups)
            {
                VendorGroupList.Add(new VendorGroupReportViewModel
                {
                    VendorConfStatus = grp.VndConfStatus != null ? grp.VndConfStatus : "",
                    BusCount = grp.BusCount != null ? Convert.ToInt32(grp.BusCount).ToString(): "",
                    CustomerName = grp.CustomerName,
                    GroupCode = grp.GroupCode,
                    GroupName = grp.GroupName,
                    ArrivalCity = grp.ArrivalCity,
                    StartCity = grp.StartCity,
                    EndCity = grp.EndCity,
                    ServiceDetail = grp.ServiceDetail,
                    Notes = grp.Notes,
                    Category = grp.Category,
                    EmployeeName = grp.EmployeeName,
                    ArrivalDate = (grp.ArrivalDate != null ? Convert.ToDateTime(grp.ArrivalDate).ToString("dd-MMM-yy") : ""),
                    FileCreatedDate = (grp.FileCreatedDate != null ? Convert.ToDateTime(grp.FileCreatedDate).ToString("dd-MMM-yy") : ""),
                    ServiceDate = (grp.ServiceDate != null ? Convert.ToDateTime(grp.ServiceDate).ToString("dd-MMM-yy") : ""),
                    Month = (grp.ArrivalDate != null ? Convert.ToDateTime(grp.ArrivalDate).ToString("MMMM") : ""),
                    NoOfPerson = grp.NoOfPerson.ToString(),
                    EstNoOfPerson = grp.EstNoOfPerson != null ? grp.EstNoOfPerson.ToString() : "",
                    IsPlane = grp.Plane == true ? "Yes" : "No",
                    Optional = grp.Optional == true ? "Yes" : "No",
                    Invoice = grp.IsInvoice == true ? "Yes" : "No",
                    IsGir = grp.IsGir == true ? "Yes" : "No",
                    Menu = grp.Menu,
                });
            }
            VendorGroupOther.Dates = ("[" +
                        Convert.ToDateTime(model.Lower).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.Upper).ToString("MM/dd/yyyy")
                        + "]");
            VendorGroupOther.Vendor = data.VendorDetail.VendorCode + "    " + data.VendorDetail.VendorName;
            VendorGroupOther.ReportTotal = data.VenGroups.Count > 1 ?
                data.VenGroups.Count.ToString() + " group @" + data.VendorDetail.VendorCode + " " + data.VendorDetail.VendorName + " between " + Convert.ToDateTime(model.Lower).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.Upper).ToString("MM/dd/yyyy")
                : data.VenGroups.Count.ToString() + " groups @" + data.VendorDetail.VendorCode + " " + data.VendorDetail.VendorName + " between " + Convert.ToDateTime(model.Lower).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.Upper).ToString("MM/dd/yyyy");
            VendorGroupOther.DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy");

            MemoryStream m_rdl = GenerateVendorGroup(model.SelectedTabColumns, model.SelectedTabColumns, VendorGroupOther, model.SelectedTab, model.PaperType);
            LocalReport localReport = new LocalReport();
            localReport.LoadReportDefinition(m_rdl);

            localReport.DataSources.Add(new ReportDataSource("MyData", VendorGroupList));

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["VendorGroupReportStream"] = Res;
            return Json(new { success = true}, JsonRequestBehavior.AllowGet);
  
        }
        public ActionResult VendorGroupReportOpen()
        {
            var Res = Session["VendorGroupReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;            
        }
        [HttpGet]
        public ActionResult FrmGuideGroupReport()
        {
            FrmGuideGroupReportViewModel Vmodel = new FrmGuideGroupReportViewModel();
            Dictionary<bool, string> IsGir = new Dictionary<bool, string>() { { true, "Yes" }, { false, "No" } };
            Vmodel.IsGir = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var element in IsGir)
            {
                Vmodel.IsGir.Add(new System.Web.WebPages.Html.SelectListItem() { Text = element.Value, Value = element.Key.ToString() });
            }
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmGuideGroupReport", Vmodel);
        }
        [HttpPost]
        public ActionResult GuideGroupReport(FrmGuideGroupReportViewModel model)
        {

            List<GuideGroupReportOtherViewModel> GuideGroupOtherList = new List<GuideGroupReportOtherViewModel>();
            List<GuideGroupReportViewModel> GuideGroupList = new List<GuideGroupReportViewModel>();
            RepManager = new ReportManager();
            GuideGroupReportBData data = RepManager.GuideGroupReport(model.SelectedGuideID != null ? Convert.ToInt32(model.SelectedGuideID) : 0, Convert.ToDateTime(model.Lower), Convert.ToDateTime(model.Upper), model.SelectedIsGir);

            foreach (var grp in data.GuideGroups)
            {
                GuideGroupList.Add(new GuideGroupReportViewModel
                {
                    StartDate = grp.StartDate != null ? Convert.ToDateTime(grp.StartDate).ToString("dd-MMM-yy") : "",
                    FinishDate = grp.FinishDate != null ? Convert.ToDateTime(grp.FinishDate).ToString("dd-MMM-yy") : "",
                    GroupCode = grp.GroupCode,
                    GroupName = grp.GroupName,
                    ArrivalDate = grp.ArrivalDate != null ? Convert.ToDateTime(grp.ArrivalDate).ToString("dd-MMM-yy") : "",
                    ArrivalCity=grp.ArrivalCity,
                    DepartureDate = grp.DepartureDate != null ? Convert.ToDateTime(grp.DepartureDate).ToString("dd-MMM-yy") : "",
                    DepartureCity=grp.DepartureCity,
                    NoOfPerson = grp.NoOfPerson.ToString(),
                });
            }
            GuideGroupOtherList.Add(new GuideGroupReportOtherViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.Lower).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.Upper).ToString("MM/dd/yyyy")
                        + "]"),
                GuideName = data.GuideDetail.FirstName + "   " + data.GuideDetail.LastName,
                Address = data.GuideDetail.Address + " " + data.GuideDetail.City + " " + data.GuideDetail.State + " " + data.GuideDetail.PostalCode,
                Fax = data.GuideDetail.Fax,
                Phone1 = data.GuideDetail.Phone1,
                Phone2 = data.GuideDetail.Phone2,
                TotalNumberOfGroups = data.GuideGroups.Count > 1
                ? data.GuideGroups.Count.ToString() + " jobs for " + data.GuideDetail.FirstName + " " + data.GuideDetail.LastName + " between " + Convert.ToDateTime(model.Lower).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.Upper).ToString("MM/dd/yyyy")
                : data.GuideGroups.Count.ToString() + " job for " + data.GuideDetail.FirstName + " " + data.GuideDetail.LastName + " between " + Convert.ToDateTime(model.Lower).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.Upper).ToString("MM/dd/yyyy"),
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            });
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/GuideGroupReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "GuideGroupOtherDataSet";
            reportDataSourceOther.Value = GuideGroupOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "GuideGroupListDataSet";
            reportDataSourceList.Value = GuideGroupList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["GuideGroupReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);

        }
        public ActionResult GuideGroupReportOpen()
        {
            var Res = Session["GuideGroupReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmGroupGuideReport()
        {
            FrmGroupGuideReportViewModel Vmodel = new FrmGroupGuideReportViewModel();
            Dictionary<bool, string> IsGir = new Dictionary<bool, string>() { { true, "Yes" }, { false, "No" } };
            Vmodel.IsGir = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var element in IsGir)
            {
                Vmodel.IsGir.Add(new System.Web.WebPages.Html.SelectListItem() { Text = element.Value, Value = element.Key.ToString() });
            }
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmGroupGuideReport", Vmodel);
        }
        [HttpPost]
        public ActionResult GroupGuideReport(FrmGroupGuideReportViewModel model)
        {
            List<GroupGuideReportOtherViewModel> GroupGuideOtherList = new List<GroupGuideReportOtherViewModel>();
            List<GroupGuideReportViewModel> GroupGuideList = new List<GroupGuideReportViewModel>();
            RepManager = new ReportManager();
            GroupGuideReportBData data = RepManager.GroupGuideReport(Convert.ToDateTime(model.Lower), Convert.ToDateTime(model.Upper), model.SelectedIsGir);

            foreach (var guide in data.GroupGuides)
            {
                    foreach (var row in guide.Rows)
                    {
                        GroupGuideList.Add(new GroupGuideReportViewModel
                        {
                            ArrivalDate = guide.ArrivalDate != null ? Convert.ToDateTime(guide.ArrivalDate).ToString("dd-MMM-yy") : "",
                            DepartureDate = guide.DepartureDate != null ? Convert.ToDateTime(guide.DepartureDate).ToString("dd-MMM-yy") : "",
                            Cancelled = guide.Cancelled != null ? Convert.ToBoolean(guide.Cancelled) : false,
                            GroupCode = guide.GroupCode,
                            NoOfPerson = guide.NoOfPerson.ToString(),
                            Nights = Convert.ToInt32((Convert.ToDateTime(guide.DepartureDate.Value.ToString()) - Convert.ToDateTime(guide.ArrivalDate.Value.ToString())).TotalDays).ToString(),
                            Guide = row.LastName + ", " + (row.FirstName.Length > 0 ? row.FirstName.FirstOrDefault() + "." : row.FirstName),
                            StartDate = row.StartDate != null ? Convert.ToDateTime(row.StartDate).ToString("dd-MMM-yy") : "",
                            FinishDate = row.FinishDate != null ? Convert.ToDateTime(row.FinishDate).ToString("dd-MMM-yy") : "",
                        });
                    }
            }
            GroupGuideOtherList.Add(new GroupGuideReportOtherViewModel
            {
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            });
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/GroupGuideReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "GroupGuideOtherDataSet";
            reportDataSourceOther.Value = GroupGuideOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "GroupGuideListDataSet";
            reportDataSourceList.Value = GroupGuideList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["GroupGuideReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GroupGuideReportOpen()
        {
            var Res = Session["GroupGuideReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmCountryCustomerGroupBalanceReport()
        {
            FrmCountryCustomerGroupBalanceReportViewModel Vmodel = new FrmCountryCustomerGroupBalanceReportViewModel();
            RepManager = new ReportManager();
            var data = RepManager.LoadFrmCountryCustomerGroupBalanceReport();
            Vmodel.Nationalities = new List<System.Web.WebPages.Html.SelectListItem>();
            Vmodel.SelectedNationalityID = null;
            foreach (var nationality in data.Nationalities)
                Vmodel.Nationalities.Add(new System.Web.WebPages.Html.SelectListItem() { Text = nationality.Value, Value = nationality.Key.ToString() });
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmCountryCustomerGroupBalanceReport", Vmodel);
        }
        [HttpPost]
        public ActionResult CountryCustomerGroupBalanceReport(FrmCountryCustomerGroupBalanceReportViewModel model)
        {

            List<CountryCustomerGroupBalanceOtherReportViewModel> BalanceOtherList = new List<CountryCustomerGroupBalanceOtherReportViewModel>();
            List<CountryCustomerGroupBalanceReportViewModel> BalanceList = new List<CountryCustomerGroupBalanceReportViewModel>();
            RepManager = new ReportManager();
            CountryCustomerGroupBalanceReportBData data = RepManager.CountryCustomerGroupBalanceReport(model.SelectedNationalityID != null ? Convert.ToInt32(model.SelectedNationalityID) : 0, Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate));
            double? TotalBalanceSum = 0;
            decimal? BalanceSum = 0;
            foreach (var rev in data.Balances)
            {
                    
                    foreach (var Balrow in rev.Rows)
                    {
                        BalanceSum=(from revs in rev.Rows select revs.Balance).Sum();
                        BalanceList.Add(new CountryCustomerGroupBalanceReportViewModel
                        {
                            Customer = rev.Customer + " " + rev.CustomerName,
                            GroupCode = Balrow.GroupCode,
                            GroupName = Balrow.GroupName,
                            ArrivalDate = Balrow.ArrivalDate != null ? Convert.ToDateTime(Balrow.ArrivalDate).ToString("dd-MMM-yy") : "",
                            FinalPayment = Balrow.FinalPayment != null ? Convert.ToDateTime(Balrow.FinalPayment).ToString("dd-MMM-yy") : "",
                            TotalPaid = DoubleStringGenerator((double?)Balrow.TotalPaid),
                            Balance = DoubleStringGenerator((double?)Balrow.Balance),
                            BalanceSum=DoubleStringGenerator((double?)BalanceSum)
                        });
                    }
                TotalBalanceSum = TotalBalanceSum + (BalanceSum !=null ? (double?)BalanceSum : 0);
            }

            BalanceOtherList.Add(new CountryCustomerGroupBalanceOtherReportViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                Nationality = data.Nationality,
                TotalBalanceSum = DoubleStringGenerator((double?)TotalBalanceSum),
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            });

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/CountryCustomerGroupBalanceReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "CustomerGroupBalanceOtherDataSet";
            reportDataSourceOther.Value = BalanceOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "CustomerGroupBalanceListDataSet";
            reportDataSourceList.Value = BalanceList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["CountryCustomerGroupBalanceReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CountryCustomerGroupBalanceReportOpen()
        {
            var Res = Session["CountryCustomerGroupBalanceReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmGroupRegionRoomDayReport()
        {
            FrmGroupRegionRoomDayReportViewModel Vmodel = new FrmGroupRegionRoomDayReportViewModel();
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmGroupRegionRoomDayReport", Vmodel);
        }
        [HttpPost]
        public ActionResult GroupRegionRoomDayReport(FrmGroupRegionRoomDayReportViewModel model)
        {
            List<GroupRegionRoomDayReportOtherViewModel> GroupRegionRoomDayOtherList = new List<GroupRegionRoomDayReportOtherViewModel>();
            List<GroupRegionRoomDayReportViewModel> GroupRegionRoomDayList = new List<GroupRegionRoomDayReportViewModel>();
            RepManager = new ReportManager();
            GroupRegionRoomDayReportBData data = RepManager.GroupRegionRoomDayReport(Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate));
            List<int> RegionIDs = (from reg in data.GroupRegionRoomDays orderby reg.RegionID select reg.RegionID).Distinct().ToList();
            Dictionary<int, int> NoOfPersonSum = new Dictionary<int, int>();
            foreach (var regID in RegionIDs)
                NoOfPersonSum.Add(regID, (from roomdays in data.GroupRegionRoomDays
                                          where roomdays.RegionID == regID
                                          select Convert.ToInt32(roomdays.NoOfPerson)).Sum());
            foreach (var regid in RegionIDs)
                GroupRegionRoomDayList.Add((from roomdays in data.GroupRegionRoomDays
                                            where roomdays.RegionID == regid
                                            select new GroupRegionRoomDayReportViewModel
                                             {
                                                 RegionCode = roomdays.RegionCode,
                                                 RegionName = roomdays.RegionName,
                                                 RoomDays = Convert.ToDouble((from roomday in data.GroupRegionRoomDays where roomday.RegionID == regid select (Convert.ToInt32((Convert.ToDateTime(roomdays.DepartureDate.Value.ToString()) - roomdays.ArrivalDate).TotalDays))).Sum()).ToString(),
                                                 PaxDays = Convert.ToDouble((NoOfPersonSum[regid] * (Convert.ToInt32((Convert.ToDateTime(roomdays.DepartureDate.Value.ToString()) - Convert.ToDateTime(roomdays.ArrivalDate)).TotalDays)))).ToString(),
                                             }).FirstOrDefault());
            GroupRegionRoomDayOtherList.Add(new GroupRegionRoomDayReportOtherViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                TotalPaxDays = Convert.ToDouble((from pax in GroupRegionRoomDayList select Convert.ToInt32(pax.PaxDays)).Sum()).ToString(),
                TotalRoomDays = Convert.ToDouble((from room in GroupRegionRoomDayList select Convert.ToInt32(room.RoomDays)).Sum()).ToString(),
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            });
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/GroupRegionRoomDayReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "GroupRegionRoomDayOtherList";
            reportDataSourceOther.Value = GroupRegionRoomDayOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "GroupRegionRoomDayList";
            reportDataSourceList.Value = GroupRegionRoomDayList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["GroupRegionRoomDayReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GroupRegionRoomDayReportOpen()
        {
            var Res = Session["GroupRegionRoomDayReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmGroupCityRoomDayReport()
        {
            FrmGroupCityRoomDayReportViewModel Vmodel = new FrmGroupCityRoomDayReportViewModel();
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmGroupCityRoomDayReport", Vmodel);
        }
        [HttpPost]
        public ActionResult GroupCityRoomDayReport(FrmGroupCityRoomDayReportViewModel model)
        {
            List<GroupCityRoomDayReportOtherViewModel> GroupCityRoomDayOtherList = new List<GroupCityRoomDayReportOtherViewModel>();
            List<GroupCityRoomDayReportViewModel> GroupCityRoomDayList = new List<GroupCityRoomDayReportViewModel>();
            RepManager = new ReportManager();
            GroupCityRoomDayReportBData data = RepManager.GroupCityRoomDayReport(Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate));
            List<string> Cities = (from city in data.GroupCityRoomDays where city.City!=null && city.City!="" orderby city.City select city.City).Distinct().ToList();
            Dictionary<string, int> NoOfPersonSum = new Dictionary<string, int>();
            foreach (var city in Cities)
                    NoOfPersonSum.Add(city, (from roomdays in data.GroupCityRoomDays
                                             where roomdays.City == city
                                             select Convert.ToInt32(roomdays.NoOfPerson)).Sum());
            foreach (var city in Cities)
                GroupCityRoomDayList.Add((from roomdays in data.GroupCityRoomDays
                                          where roomdays.City == city
                                          select new GroupCityRoomDayReportViewModel
                                            {
                                                City = roomdays.City,
                                                StateID = roomdays.StateID,
                                                RoomDays = Convert.ToDouble((from roomday in data.GroupCityRoomDays where roomday.City == city select (Convert.ToInt32((Convert.ToDateTime(roomdays.DepartureDate.Value.ToString()) - roomdays.ArrivalDate).TotalDays))).Sum()).ToString(),
                                                PaxDays = Convert.ToDouble((NoOfPersonSum[city] * (Convert.ToInt32((Convert.ToDateTime(roomdays.DepartureDate.Value.ToString()) - Convert.ToDateTime(roomdays.ArrivalDate)).TotalDays)))).ToString(),
                                            }).FirstOrDefault());
            GroupCityRoomDayOtherList.Add(new GroupCityRoomDayReportOtherViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                TotalPaxDays = Convert.ToDouble((from pax in GroupCityRoomDayList select Convert.ToInt32(pax.PaxDays)).Sum()).ToString(),
                TotalRoomDays = Convert.ToDouble((from room in GroupCityRoomDayList select Convert.ToInt32(room.RoomDays)).Sum()).ToString(),
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            });
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/GroupCityRoomDayReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "GroupCityRoomDayOtherList";
            reportDataSourceOther.Value = GroupCityRoomDayOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "GroupCityRoomDayList";
            reportDataSourceList.Value = GroupCityRoomDayList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["GroupCityRoomDayReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GroupCityRoomDayReportOpen()
        {
            var Res = Session["GroupCityRoomDayReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmCustomerARDaysReport()
        {
            FrmCustomerARDayesReportViewModel Vmodel = new FrmCustomerARDayesReportViewModel();
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmCustomerARDaysReport", Vmodel);
        }
        [HttpPost]
        public ActionResult CustomerARDaysReport(FrmCustomerARDayesReportViewModel model)
        {

            List<CustomerARDayesOtherReportViewModel> ARDayesOtherList = new List<CustomerARDayesOtherReportViewModel>();
            List<CustomerARDayesReportViewModel> ARDayesList = new List<CustomerARDayesReportViewModel>();
            RepManager = new ReportManager();
            CustomerARDayesReportBData data = RepManager.CustomerARDayesReport(model.SelectedCustomerID != null ? Convert.ToInt32(model.SelectedCustomerID) : 0, Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate));
            ARDayesOtherList.Add(new CustomerARDayesOtherReportViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                Customer = data.CustomerDetail.CustomerCode + "   " + data.CustomerDetail.OrganizationName,
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
                Total = DoubleStringGenerator((double?)(from ardays in data.ARDayes
                                                        select Convert.ToDouble(ardays.Balance)).Sum()),
                Total_0_30_DayesBalance = (from ardayes in data.ARDayes
                                            where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 0
                                            && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 30
                                            select Convert.ToDouble(ardayes.Balance)).Any() ? DoubleStringGenerator((double?)(from ardayes in data.ARDayes
                                                                                                                              where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 0
                                                                                                                              && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 30
                                                                                                                              select Convert.ToDouble(ardayes.Balance)).Sum()) : "",
                Total_30_60_DayesBalance = (from ardayes in data.ARDayes
                                            where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 30
                                     && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 60
                                            select Convert.ToDouble(ardayes.Balance)).Any() ? DoubleStringGenerator((double?)(from ardayes in data.ARDayes
                                                                                                                              where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 30
                                                                                                                              && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 60
                                                                                                                              select Convert.ToDouble(ardayes.Balance)).Sum()) : "",
                Total_60_90_DayesBalance = (from ardayes in data.ARDayes
                                            where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 60
                                     && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 90
                                            select Convert.ToDouble(ardayes.Balance)).Any() ? DoubleStringGenerator((double?)(from ardayes in data.ARDayes
                                                                                                                              where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 60
                                                                                                                              && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 90
                                                                                                                              select Convert.ToDouble(ardayes.Balance)).Sum()) : "",
                Total_90_120_DayesBalance = (from ardayes in data.ARDayes
                                            where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 90
                                     && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 120
                                             select Convert.ToDouble(ardayes.Balance)).Any() ? DoubleStringGenerator((double?)(from ardayes in data.ARDayes
                                                                                                                              where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 90
                                                                                                                              && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 120
                                                                                                                              select Convert.ToDouble(ardayes.Balance)).Sum()) : "",
                Total_Over120_DayesBalance = (from ardayes in data.ARDayes
                                              where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 120
                                              select Convert.ToDouble(ardayes.Balance)).Any() ? DoubleStringGenerator((double?)(from ardayes in data.ARDayes
                                                                                                                                where Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 120
                                                                                                                                select Convert.ToDouble(ardayes.Balance)).Sum()) : "",
            });
            foreach (var ardayes in data.ARDayes)
            {
                ARDayesList.Add(new CustomerARDayesReportViewModel
                {
                    GroupCode = ardayes.GroupCode,
                    GroupName = ardayes.GroupName,
                    ArrivalDate = ardayes.ArrivalDate != null ? Convert.ToDateTime(ardayes.ArrivalDate).ToString("dd-MMM-yy") : "",
                    TotalDays= Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays).ToString(),
                    DayesBalance_0_30_ = (Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 0 && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 30) ? DoubleStringGenerator((double?)ardayes.Balance) : "",
                    DayesBalance_30_60_ = (Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 30 && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 60) ? DoubleStringGenerator((double?)ardayes.Balance) : "",
                    DayesBalance_60_90_ = (Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 60 && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 90) ? DoubleStringGenerator((double?)ardayes.Balance) : "",
                    DayesBalance_90_120_ = (Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 90 && Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) <= 120) ? DoubleStringGenerator((double?)ardayes.Balance) : "",
                    DayesBalance_Over120_ = (Convert.ToInt32((DateTime.Now - Convert.ToDateTime(ardayes.FinalDue.Value.ToString())).TotalDays) > 120) ? DoubleStringGenerator((double?)ardayes.Balance) : "",
                });
            }

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/CustomerARDaysReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "CustomerARDayesOtherDataSet";
            reportDataSourceOther.Value = ARDayesOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "CustomerARDayesListDataSet";
            reportDataSourceList.Value = ARDayesList;
            localReport.DataSources.Add(reportDataSourceList);


            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["CustomerARDaysReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CustomerARDaysReportOpen()
        {
            var Res = Session["CustomerARDaysReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmCustomerPaymentTypeReport()
        {
            FrmCustomerPaymentTypeReportViewModel Vmodel = new FrmCustomerPaymentTypeReportViewModel();
            RepManager = new ReportManager();
            var data = RepManager.LoadFrmCustomerPaymentTypeReport();
            Vmodel.PaymentTypes = new List<System.Web.WebPages.Html.SelectListItem>();
            Vmodel.SelectedPaymentTypeID = null;
            foreach (var paytype in data.PaymentTypes)
                Vmodel.PaymentTypes.Add(new System.Web.WebPages.Html.SelectListItem() { Text = paytype.Value, Value = paytype.Key.ToString() });
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmCustomerPaymentTypeReport", Vmodel);
        }
        [HttpPost]
        public ActionResult CustomerPaymentTypeReport(FrmCustomerPaymentTypeReportViewModel model)
        {

            List<CustomerPaymentTypeOtherReportViewModel> PayTypeOtherList = new List<CustomerPaymentTypeOtherReportViewModel>();
            List<CustomerPaymentTypeReportViewModel> PayTypeList = new List<CustomerPaymentTypeReportViewModel>();
            RepManager = new ReportManager();
            CustomerPaymentTypeReportBData data = RepManager.CustomerPaymentTypeReport(model.SelectedPaymentTypeID != null ? Convert.ToInt32(model.SelectedPaymentTypeID) : 0, Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate));
            foreach (var paytype in data.PaymentTypes)
            {
                if (paytype.Rows.Count == 0)
                {
                    PayTypeList.Add(new CustomerPaymentTypeReportViewModel
                    {
                        LineNo = paytype.LineNo != null ? Convert.ToInt32(paytype.LineNo) : 0,
                        PaymentDate = paytype.PaymentDate != null ? Convert.ToDateTime(paytype.PaymentDate).ToString("dd-MMM-yy") : "",
                        Payment = DoubleStringGenerator((double?)paytype.Payment),
                        CustomerCode = paytype.CustomerCode,
                        CustomerName = paytype.OrganizationName,
                        Description = paytype.Description,
                        Refunded = paytype.Refunded != null ? DoubleStringGenerator((double?)paytype.Refunded) : "",
                        GroupCode = "",
                        GroupName = "",
                        Balance = "$0",
                        CustomerBalance = DoubleStringGenerator((double?)data.PaymentTypes.Where(ptype => ptype.CustomerID == paytype.CustomerID).Select(ptype => ptype.Rows.Select(p => p.Balance).Sum()).Sum()),
                    });
                }
                else
                {
                    foreach (var paytyperow in paytype.Rows)
                    {
                        PayTypeList.Add(new CustomerPaymentTypeReportViewModel
                        {
                            LineNo = paytype.LineNo != null ? Convert.ToInt32(paytype.LineNo) : 0,
                            Description = paytype.Description,
                            CustomerCode = paytype.CustomerCode,
                            CustomerName = paytype.OrganizationName,
                            PaymentDate = paytype.PaymentDate != null ? Convert.ToDateTime(paytype.PaymentDate).ToString("dd-MMM-yy") : "",
                            Payment = DoubleStringGenerator((double?)paytype.Payment),
                            Refunded = paytype.Refunded != null ? DoubleStringGenerator((double?)paytype.Refunded) : "",
                            GroupCode = paytyperow.GroupCode,
                            GroupName = paytyperow.GroupName,
                            Balance = DoubleStringGenerator((double?)paytyperow.Balance),
                            CustomerBalance = DoubleStringGenerator((double?)data.PaymentTypes.Where(ptype=>ptype.CustomerID==paytype.CustomerID).Select(ptype => ptype.Rows.Select(p=>p.Balance).Sum()).Sum()),
                        });
                    }
                }
            }
            PayTypeOtherList.Add(new CustomerPaymentTypeOtherReportViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                PayTypeCode = data.PaymentTypeDetail.PayTypeCode,
                PayTypeDesc = data.PaymentTypeDetail.PayTypeDesc,
                ReportTotal = DoubleStringGenerator((double?)data.PaymentTypes.Select(ptype=>ptype.Rows.Select(row=>row.Balance).Sum()).Sum()),
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            });
           

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/CustomerPaymentTypeReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "CustomerPaymentTypeOtherDataSet";
            reportDataSourceOther.Value = PayTypeOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "CustomerPaymentTypeListDataSet";
            reportDataSourceList.Value = PayTypeList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["CustomerPaymentTypeReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CustomerPaymentTypeReportOpen()
        {
            var Res = Session["CustomerPaymentTypeReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmCustomerRefundReport()
        {
            FrmCustomerRefundReportViewModel Vmodel = new FrmCustomerRefundReportViewModel();
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmCustomerRefundReport", Vmodel);
        }
        [HttpPost]
        public ActionResult CustomerRefundReport(FrmCustomerRefundReportViewModel model)
        {

            List<CustomerRefundOtherReportViewModel> RefundOtherList = new List<CustomerRefundOtherReportViewModel>();
            List<CustomerRefundReportViewModel> RefundList = new List<CustomerRefundReportViewModel>();
            RepManager = new ReportManager();
            CustomerRefundReportBData data = RepManager.CustomerRefundReport(model.SelectedCustomerID != null ? Convert.ToInt32(model.SelectedCustomerID) : 0, Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate));

            RefundOtherList.Add(new CustomerRefundOtherReportViewModel
            {
                Dates = ("[" +
                        Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
                        + " - " +
                        Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
                        + "]"),
                Customer = data.CustomerRefundDetail.CustomerCode + "   " + data.CustomerRefundDetail.OrganizationName,
                ReportTotal = DoubleStringGenerator((double?)data.Refunds.Select(ptype => ptype.Rows.Select(row => row.Refunded).Sum()).Sum()),
                DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            });
            foreach (var refund in data.Refunds)
            {
                if (refund.Rows.Count == 0)
                {
                    RefundList.Add(new CustomerRefundReportViewModel
                    {
                        LineNo = refund.LineNo != null ? Convert.ToInt32(refund.LineNo) : 0,
                        Description = refund.Description,
                        PayTypeCode = refund.PayTypeCode,
                        PaymentDate = refund.PaymentDate != null ? Convert.ToDateTime(refund.PaymentDate).ToString("dd-MMM-yy") : "",
                        Refund = refund.Debit != null ? DoubleStringGenerator((double?)refund.Debit) : "",
                        GroupCode = "",
                        GroupName = "",
                        Detail = "$0",
                    });
                }
                else
                    foreach (var refrow in refund.Rows)
                    {
                        RefundList.Add(new CustomerRefundReportViewModel
                        {
                            LineNo = refund.LineNo != null ? Convert.ToInt32(refund.LineNo) : 0,
                            Description = refund.Description,
                            PayTypeCode = refund.PayTypeCode,
                            PaymentDate = refund.PaymentDate != null ? Convert.ToDateTime(refund.PaymentDate).ToString("dd-MMM-yy") : "",
                            Refund = refund.Debit != null ? DoubleStringGenerator((double?)refund.Debit) : "",
                            GroupCode = refrow.GroupCode,
                            GroupName = refrow.GroupName,
                            Detail = DoubleStringGenerator((double?)refrow.Refunded),
                        });
                    }
            }

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/CustomerRefundReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "CustomerRefundOtherDataSet";
            reportDataSourceOther.Value = RefundOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "CustomerRefundListDataSet";
            reportDataSourceList.Value = RefundList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError); 
            Session["CustomerRefundReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CustomerRefundReportOpen()
        {
            var Res = Session["CustomerRefundReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmGuideListReport()
        {
            FrmGuideListReportViewModel Vmodel = new FrmGuideListReportViewModel();
            RepManager = new ReportManager();
            var data = RepManager.LoadFrmGuideListReport();
            Vmodel.Regions = new List<System.Web.WebPages.Html.SelectListItem>();
            Vmodel.SelectedRegionID = null;
            foreach (var region in data.Regions)
                Vmodel.Regions.Add(new System.Web.WebPages.Html.SelectListItem() { Text = region.Value, Value = region.Key.ToString() });
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmGuideListReport", Vmodel);
        }
        [HttpPost]
        public ActionResult GuideListReport(FrmGuideListReportViewModel model)
        {

            List<GuideListOtherReportViewModel> GuideOtherList = new List<GuideListOtherReportViewModel>();
            List<GuideListReportViewModel> GuideList = new List<GuideListReportViewModel>();
            RepManager = new ReportManager();
            GuideListReportBData data = RepManager.GuideListReport(model.SelectedRegionID != null ? Convert.ToInt32(model.SelectedRegionID) : 0);

            GuideOtherList.Add(new GuideListOtherReportViewModel
            {
                RegionCode = data.RegionCode != null ? data.RegionCode : "Undetermined",
                DateTimeNow = "Guide List         " + DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            });
            foreach (var guide in data.Guides)
            {
                GuideList.Add(new GuideListReportViewModel
                {
                    CityStateID = (guide.City + " / " + guide.StateID).ToUpper(),
                    Guide = ((guide.Sex == null) || (guide.Sex == 0))
                             ? ("Ms. " + guide.FirstName + " " + guide.LastName).ToUpper()
                             : ("Mr. " + guide.FirstName + " " + guide.LastName).ToUpper(),
                    Phone1 = "Phone 1: " + guide.Phone1,
                    Phone2 = "           2:  " + guide.Phone2,
                    Fax = "Fax: " + guide.Fax,
                    Note = guide.Note,
                    Address = ((guide.Address != null && guide.Address != "") ? guide.Address + ", " : "") + ((guide.City != null && guide.City != "") ? guide.City + ", " : "") + ((guide.StateID != null && guide.StateID != "") ? guide.StateID + ", " : "") + guide.PostalCode,
                });
            }

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/GuideListReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "GuideListOtherDataSet";
            reportDataSourceOther.Value = GuideOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "GuideListDataSet";
            reportDataSourceList.Value = GuideList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["GuideListReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GuideListReportOpen()
        {
            var Res = Session["GuideListReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        [HttpGet]
        public ActionResult FrmHotelContractsReport()
        {
            FrmHotelContractsReportViewModel Vmodel = new FrmHotelContractsReportViewModel();
            RepManager = new ReportManager();
            var data = RepManager.LoadFrmHotelContractsReport();
            Vmodel.Regions = new List<System.Web.WebPages.Html.SelectListItem>();
            Vmodel.SelectedRegionID = null;
            foreach (var region in data.Regions)
                Vmodel.Regions.Add(new System.Web.WebPages.Html.SelectListItem() { Text = region.Value, Value = region.Key.ToString() });
            Vmodel.Seasons = new List<System.Web.WebPages.Html.SelectListItem>();
            Vmodel.SelectedSeasonID = null;
            foreach (var season in data.Seasons)
                Vmodel.Seasons.Add(new System.Web.WebPages.Html.SelectListItem() { Text = season.Value, Value = season.Key.ToString() });
            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmHotelContractsReport", Vmodel);
        }
        [HttpGet]
        public ActionResult HotelContractsReport(int? RegionID, int? SeasonID)
        {

            List<GuideListOtherReportViewModel> GuideOtherList = new List<GuideListOtherReportViewModel>();
            List<GuideListReportViewModel> GuideList = new List<GuideListReportViewModel>();
            RepManager = new ReportManager();
            HotelContractsReportBData data = RepManager.HotelContractsReport(RegionID != null ? Convert.ToInt32(RegionID) : 0, SeasonID != null ? Convert.ToInt32(SeasonID) : 0);

            //GuideOtherList.Add(new GuideListOtherReportViewModel
            //{
            //    RegionCode = data.RegionCode != null ? data.RegionCode : "Undetermined",
            //    DateTimeNow = "Guide List         " + DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            //});
            //foreach (var guide in data.Guides)
            //{
            //    GuideList.Add(new GuideListReportViewModel
            //    {
            //        CityStateID = (guide.City + " / " + guide.StateID).ToUpper(),
            //        Guide = ((guide.Sex == null) || (guide.Sex == 0))
            //                 ? ("Ms. " + guide.FirstName + " " + guide.LastName).ToUpper()
            //                 : ("Mr. " + guide.FirstName + " " + guide.LastName).ToUpper(),
            //        Phone1 = "Phone 1: " + guide.Phone1,
            //        Phone2 = "           2:  " + guide.Phone2,
            //        Fax = "Fax: " + guide.Fax,
            //        Note = guide.Note,
            //        Address = guide.Address + ", " + guide.City + ", " + guide.StateID + ", " + guide.PostalCode,
            //    });
            //}

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/GuideListReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "GuideListOtherDataSet";
            reportDataSourceOther.Value = GuideOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "GuideListDataSet";
            reportDataSourceList.Value = GuideList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            var GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            if (GeneretedReport != null)
                return File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);

        }
        [HttpGet]
        public ActionResult VConfirmBreakDown(int VendorID, int GroupID, string ArrivalDate)
        {

            RepManager = new ReportManager();
            VConfirmBreakDownReportBData data = RepManager.VConfirmBreakDownReport(VendorID, GroupID, Convert.ToDateTime(ArrivalDate));
            List<VConfirmBreakDownOtherReportViewModel> VConfirmBreakDownOtherList = new List<VConfirmBreakDownOtherReportViewModel>();
            List<VConfirmBreakDownReportViewModel> VConfirmBreakDownList = new List<VConfirmBreakDownReportViewModel>();
            List<VConfirmExtraBreakDownReportViewModel> VConfirmBreakDownExtraList = new List<VConfirmExtraBreakDownReportViewModel>();
            data.BreakDown.RemoveAll(x => (x.Qty == 0) || (x.Qty == null) || (x.Price == 0) || (x.Price == null));
            data.BreakDown.RemoveAll(x => (x.ServiceID == 6 || x.ServiceID == 7 || x.ServiceID == 70 || x.ServiceID == 71) && (x.ProductID != 1));
            data.BreakDownExtra.RemoveAll(x => (x.Qty == 0) || (x.Qty == null) || (x.Price == 0) || (x.Price == null));
            if(data.BreakDown.Any(bdown=>bdown.ServiceID == 103))
            {
                foreach(var bd in data.BreakDown)
                {
                    if(bd.ServiceID == 103)
                    {
                        bd.ServiceTypeID = 1000;
                        bd.ServiceTypeCode = "Baggage";
                    }
                }
            }
            //foreach (var bd in data.BreakDown)
            //{
            //        bd.ServiceTypeCode = "A";
            //}
            if (data.BreakDownExtra.Any(bdown => bdown.ServiceID == 103))
            {
                foreach (var bd in data.BreakDownExtra)
                {
                    if (bd.ServiceID == 103)
                    {
                        bd.ServiceTypeID = 1000;
                        bd.ServiceTypeCode = "Baggage";
                    }
                }
            }
            VConfirmBreakDownOtherList.Add(new VConfirmBreakDownOtherReportViewModel
            {
                CompanyName = data.CompanyDetail.CompanyName,
                Address=data.CompanyDetail.Address + ", " + data.CompanyDetail.City.ToUpper() + ", " + data.CompanyDetail.State + " " + data.CompanyDetail.PostalCode,
                CompanyPhone = data.CompanyDetail.PhoneNumber,
                CompanyFax = data.CompanyDetail.FaxNumber,
                GroupCode = data.GroupDetail.GroupCode,
                GroupName = data.GroupDetail.GroupName,
                ArrivalDate = data.GroupDetail.ArrivalDate.ToString("dd/MMM/yy"),
                ArrivalTime = data.GroupDetail.ArrivalTime != null ? Convert.ToDateTime(data.GroupDetail.ArrivalTime).ToString("hh:mm:ss tt") : "",
                DepartureDate = data.GroupDetail.DepartureDate != null ? Convert.ToDateTime(data.GroupDetail.DepartureDate).ToString("dd/MMM/yy") : "",
                DepartureTime = data.GroupDetail.DepartureTime != null ? Convert.ToDateTime(data.GroupDetail.DepartureTime).ToString("hh:mm:ss tt") : "",
                Pax = data.GroupDetail.Pax != null ? data.GroupDetail.Pax.ToString() : "0",
                GuideCount = data.GroupDetail.GuideCount != null ? data.GroupDetail.GuideCount.ToString() : "0",
               // PaxPlus = data.GroupDetail.PaxPlus !=null ? data.GroupDetail.PaxPlus.ToString() : "0",
               // VendorRef=data.GroupDetail.VendorRef,
                Nationality = data.GroupDetail.Nationality,
                Luggage = DoubleStringGeneratorF((double?)data.GroupDetail.Luggage),
                Tax = Convert.ToDouble(data.GroupDetail.Tax).ToString("F") + "%",
                OccTax = DoubleStringGeneratorF((double?)data.GroupDetail.OccTax),
                ATTN = data.VendorDetail.ContactName != null ? data.VendorDetail.ContactName.ToUpper() : "" + " / " + data.VendorDetail.ContactTitle != null ? data.VendorDetail.ContactTitle.ToUpper() : "",
                VendorName = data.VendorDetail.VendorName != null ? data.VendorDetail.VendorName.ToUpper() : "",
                VendorPhone = data.VendorDetail.VendorPhoneNumber != null ?  data.VendorDetail.VendorPhoneNumber : "",
                VendorFax = data.VendorDetail.VendorFaxNumber != null ? data.VendorDetail.VendorFaxNumber : "",
                Baggage = data.BreakDownAllDetail.Baggage != null ? data.BreakDownAllDetail.Baggage.ToString() : "",
                BaggageLuggage = DoubleStringGeneratorF((double?)(data.BuggageQty)),
                Less = DoubleStringGeneratorF((double?)data.BreakDownAllDetail.Less),
                LessARoom = DoubleStringGeneratorF((double?)(data.BreakDownAllDetail.LessARoom)),
                LessNRoom = data.BreakDownAllDetail.LessNRoom.ToString(),
                Comp = data.BreakDownAllDetail.Comp.ToString(),
                SumOfSentE = data.BreakDownAllDetail.SumOfSentE.ToString(),
                LessDeposit = DoubleStringGeneratorF((double?)(data.BreakDownAllDetail.LessDeposit)),
            });
            double? TotalForAllService = 0;
            double? TotalAmountDue = 0;
            foreach (var rows in data.BreakDown)
            {
                    VConfirmBreakDownList.Add(new VConfirmBreakDownReportViewModel
                    {
                        ServiceTypeID = rows.ServiceTypeID,
                        ServiceTypeCode = rows.ServiceTypeCode,
                        ServiceCode = rows.ServiceCode,
                        Qty = rows.Qty.ToString(),
                        Day = Convert.ToInt32((Convert.ToDateTime(rows.EndDate) - rows.ArrivalDate).TotalDays),
                        Price = DoubleStringGeneratorF((double?)rows.Price),
                        ExtPrice = DoubleStringGeneratorF((double?)(rows.Qty * Convert.ToDouble(rows.Price))),
                        OccTax = rows.ServiceTypeID == 1 ? DoubleStringGeneratorF((double?)(rows.Qty * Convert.ToDouble(data.GroupDetail.OccTax))) : "",
                        SalesTax = rows.ServiceTypeID == 1 ? DoubleStringGeneratorF((double?)(rows.Qty * Convert.ToDouble(rows.Price) * Convert.ToDouble(data.GroupDetail.Tax)/100)) : "",
                        Total = rows.ServiceTypeID == 1 ? DoubleStringGeneratorF((double?)((rows.Qty * Convert.ToDouble(rows.Price)) * (1 + Convert.ToDouble(data.GroupDetail.Tax/100)) + (rows.Qty * Convert.ToDouble(data.GroupDetail.OccTax)))) : DoubleStringGeneratorF((double?)((rows.Qty * Convert.ToDouble(rows.Price)))),
                        ServiceTypeTotal = rows.ServiceTypeID == 1
                                    ? DoubleStringGeneratorF((double?)((from bdownlist in data.BreakDown where bdownlist.ServiceTypeID == 1 select (bdownlist.Qty * Convert.ToDouble(bdownlist.Price))).Sum() * (1 + Convert.ToDouble(data.GroupDetail.Tax / 100)) + (from bdownlist in data.BreakDown where bdownlist.ServiceTypeID == 1 select (bdownlist.Qty * Convert.ToDouble(data.GroupDetail.OccTax))).Sum()))
                                    : DoubleStringGeneratorF((double?)(from bdownlist in data.BreakDown where bdownlist.ServiceTypeID == rows.ServiceTypeID select (bdownlist.Qty * Convert.ToDouble(bdownlist.Price))).Sum()),
                    });
                    TotalForAllService = TotalForAllService + (rows.ServiceTypeID == 1  ? (double?)((rows.Qty * Convert.ToDouble(rows.Price)) * (1 + Convert.ToDouble(data.GroupDetail.Tax / 100)) + (rows.Qty * Convert.ToDouble(data.GroupDetail.OccTax))) : (double?)((rows.Qty * Convert.ToDouble(rows.Price))));
            }
            foreach (var rows in data.BreakDownExtra)
            {
                VConfirmBreakDownExtraList.Add(new VConfirmExtraBreakDownReportViewModel
                {
                    ServiceTypeID = rows.ServiceTypeID,
                    ServiceTypeCode = rows.ServiceTypeCode,
                    ServiceCode = rows.ServiceCode,
                    Qty = rows.Qty.ToString(),
                    StartDate = rows.StartDate != null ? Convert.ToDateTime(rows.StartDate).ToString("dd-MMM-yy") : "",
                    EndDate = rows.EndDate != null ? Convert.ToDateTime(rows.EndDate).ToString("dd-MMM-yy") : "",
                    Price = DoubleStringGeneratorF((double?)rows.Price),
                    ExtPrice = DoubleStringGeneratorF((double?)(rows.Qty * Convert.ToDouble(rows.Price))),
                    OccTax = rows.ServiceTypeID == 1 ? DoubleStringGeneratorF((double?)(rows.Qty * Convert.ToDouble(data.GroupDetail.OccTax))) : "",
                    SalesTax = rows.ServiceTypeID == 1 ? DoubleStringGeneratorF((double?)(rows.Qty * Convert.ToDouble(rows.Price) * Convert.ToDouble(data.GroupDetail.Tax) / 100)) : "",
                    Total = rows.ServiceTypeID == 1 ? DoubleStringGeneratorF((double?)((rows.Qty * Convert.ToDouble(rows.Price)) * (1 + Convert.ToDouble(data.GroupDetail.Tax / 100)) + (rows.Qty * Convert.ToDouble(data.GroupDetail.OccTax)))) : DoubleStringGeneratorF((double?)((rows.Qty * Convert.ToDouble(rows.Price)))),
                    ServiceTypeTotal = rows.ServiceTypeID == 1
                                ? DoubleStringGeneratorF((double?)((from bdownlist in data.BreakDownExtra where bdownlist.ServiceTypeID == 1 select (bdownlist.Qty * Convert.ToDouble(bdownlist.Price))).Sum() * (1 + Convert.ToDouble(data.GroupDetail.Tax / 100)) + (from bdownlist in data.BreakDownExtra where bdownlist.ServiceTypeID == 1 select (bdownlist.Qty * Convert.ToDouble(data.GroupDetail.OccTax))).Sum()))
                                : DoubleStringGeneratorF((double?)(from bdownlist in data.BreakDownExtra where bdownlist.ServiceTypeID == rows.ServiceTypeID select (bdownlist.Qty * Convert.ToDouble(bdownlist.Price))).Sum()),
                });
                TotalForAllService = TotalForAllService + (rows.ServiceTypeID == 1 ? (double?)((rows.Qty * Convert.ToDouble(rows.Price)) * (1 + Convert.ToDouble(data.GroupDetail.Tax / 100)) + (rows.Qty * Convert.ToDouble(data.GroupDetail.OccTax))) : (double?)((rows.Qty * Convert.ToDouble(rows.Price))));
            }
            TotalAmountDue = TotalForAllService - Convert.ToDouble(data.BreakDownAllDetail.Less) - Convert.ToDouble(data.BreakDownAllDetail.LessDeposit);
            VConfirmBreakDownOtherList[0].TotalForAllServices = DoubleStringGeneratorF(TotalForAllService);
            VConfirmBreakDownOtherList[0].TotalAmountDue = DoubleStringGeneratorF(TotalAmountDue);
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/VConfirmBreakDownReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "VConfirmBreakDownOtherDataSet";
            reportDataSourceOther.Value = VConfirmBreakDownOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "VConfirmBreakDownListDataSet";
            reportDataSourceList.Value = VConfirmBreakDownList.OrderBy(vcnf => vcnf.ServiceTypeID).ToList();
            localReport.DataSources.Add(reportDataSourceList);

            ReportDataSource reportDataSourceExtraList = new ReportDataSource();
            reportDataSourceExtraList.Name = "VConfirmExtraBreakDownListDataSet";
            reportDataSourceExtraList.Value = VConfirmBreakDownExtraList.OrderBy(vcnf => vcnf.ServiceTypeID).ToList();
            localReport.DataSources.Add(reportDataSourceExtraList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            var GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            if (GeneretedReport != null)
                return File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);

        }
        [HttpGet]
        public ActionResult AuthorizationFormReport(int AuthFormID)
        {

            RepManager = new ReportManager();
            OperationAmexVendorReportBData data = RepManager.AuthorizationFormReport(AuthFormID);
            List<OperationAmexVendorOtherReportViewModel> AuthorizationFormOtherList = new List<OperationAmexVendorOtherReportViewModel>();
            AuthorizationFormOtherList.Add(new OperationAmexVendorOtherReportViewModel
            {
                CompanyPhone = data.CompanyPhone != null ? data.CompanyPhone : " ",
                CompanyFax = data.CompanyFax != null ? data.CompanyFax : " ",
                Attention = data.Attention,
                CompanyAddress = data.CompanyAddress != null ? data.CompanyAddress : " ",
                VendorName = data.VendorName != null ? data.VendorName : " ",
                GroupCode = data.GroupCode != null ? data.GroupCode : " ",
                GroupName = data.GroupName != null ? data.GroupName : " ",
                Date = data.Date != null ? Convert.ToDateTime(data.Date).ToString("dd/MMM/yy") : "",
                AuthorizedAmount = data.AuthorizedAmount != null ? Convert.ToDecimal(data.AuthorizedAmount).ToString("F") : "0",
                PaymentFor = data.PaymentFor,
                PreparedBy = data.PreparedBy,
                CardType = data.CardType,
                PlaceHolderName = data.PlaceHolderName,
                CardNumber = data.CardNumber,
                CardValidToDate = data.CardValidToDate != null ? "EXP. DATE  " + Convert.ToDateTime(data.CardValidToDate).ToString("MM/yyy") : "",
                Curr = data.Curr,
            });
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/OperationAmexVendorReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "OperationAmexVendorOtherDataSet";
            reportDataSourceOther.Value = AuthorizationFormOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            var GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            if (GeneretedReport != null)
                return File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);

        }
        [HttpGet]
        public ActionResult FrmGroupBreakDownReport()
        {
            FrmGroupBreakDownReportViewModel Vmodel = new FrmGroupBreakDownReportViewModel();
            Vmodel.IsGir = new List<System.Web.WebPages.Html.SelectListItem>();
            Vmodel.IsGir.Add(new System.Web.WebPages.Html.SelectListItem() { Text = "Yes", Value = "True" });
            Vmodel.IsGir.Add(new System.Web.WebPages.Html.SelectListItem() { Text = "No", Value = "False" });

            this.SetPermission(Vmodel, AllPermVModel);
            return View("FrmGroupBreakDownReport", Vmodel);
        }
        [HttpPost]
        public ActionResult GroupBreakDownReport(FrmGroupBreakDownReportViewModel model)
        {

            List<GroupBreakDownReportOtherViewModel> GroupBreakDownOtherList = new List<GroupBreakDownReportOtherViewModel>();
            List<GroupBreakDownReportViewModel> GroupBreakDownList = new List<GroupBreakDownReportViewModel>();
            RepManager = new ReportManager();
            var data = RepManager.GroupBreakDownReport(Convert.ToDateTime(model.BeginningDate), Convert.ToDateTime(model.EndingDate), model.SelectedIsGir);

            foreach (var grp in data.Groups)
            {
                GroupBreakDownList.Add(new GroupBreakDownReportViewModel
                {
                    GroupCode = grp.GroupCode,
                    GroupName = grp.GroupName,
                    //  Customer = grp.cu
                    ArrivalDate = grp.ArrivalDate != null ? Convert.ToDateTime(grp.ArrivalDate).ToString("dd-MMM-yy") : "",
                    DepartureDate = grp.DepartureDate != null ? Convert.ToDateTime(grp.DepartureDate).ToString("dd-MMM-yy") : "",
                    ArrivalCity = grp.ArrivalCity,
                    DepartureCity = grp.DepartureCity,
                    NoOfPerson = grp.NoOfPerson.ToString(),
                    IsGir = grp.IsGir == true ? "Yes" : grp.AsGir == true ? "Yes" : "No",
                });
            }
            //CustomerGroupOtherList.Add(new CustomerGroupReportOtherViewModel
            //{
            //    Dates = ("[" +
            //            Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy")
            //            + " - " +
            //            Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
            //            + "]"),
            //    Customer = data.CustomerDetail.CustomerCode + "   " + data.CustomerDetail.OrganizationName,
            //    CustomerTotal = data.Groups.Count > 1 ?
            //    data.Groups.Count.ToString() + " [" + data.CustomerDetail.CustomerCode + "] groups between " + Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
            //    : data.Groups.Count.ToString() + " [" + data.CustomerDetail.CustomerCode + "] group between " + Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy"),
            //    ReportTotal = data.Groups.Count > 1 ?
            //    "Total " + data.Groups.Count.ToString() + " groups between " + Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy")
            //    : "Total " + data.Groups.Count.ToString() + " group between " + Convert.ToDateTime(model.BeginningDate).ToString("MM/dd/yyyy") + " and " + Convert.ToDateTime(model.EndingDate).ToString("MM/dd/yyyy"),
            //    DateTimeNow = DateTime.Now.ToString("dddd, MMMM d, yyyy"),
            //    NoOfPersonSum = PersonSum.ToString(),
            //});
            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Report/GroupBreakDownReport.rdlc");

            ReportDataSource reportDataSourceOther = new ReportDataSource();
            reportDataSourceOther.Name = "GroupBreakDownOtherDataSet";
            reportDataSourceOther.Value = GroupBreakDownOtherList;
            localReport.DataSources.Add(reportDataSourceOther);

            ReportDataSource reportDataSourceList = new ReportDataSource();
            reportDataSourceList.Name = "GroupBreakDownListDataSet";
            reportDataSourceList.Value = GroupBreakDownList;
            localReport.DataSources.Add(reportDataSourceList);

            MessageBoxViewModel GenReportError = new MessageBoxViewModel();
            byte[] GeneretedReport = null;
            if (model.RunExcel)
                GeneretedReport = ReportGeneratorExcel(localReport, ref GenReportError);
            else
                GeneretedReport = ReportGenerator(localReport, ref GenReportError);
            FileContentResult Res = null;
            if (GeneretedReport != null)
                Res = model.RunExcel ? File(GeneretedReport, "application/vnd.ms-excel") : File(GeneretedReport, "application/pdf");
            else
                return View("MessageBox", GenReportError);
            Session["GroupBreakDownReportStream"] = Res;
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GroupBreakDownReportOpen()
        {
            var Res = Session["GroupBreakDownReportStream"] as FileContentResult;
            if (Res == null)
                return new EmptyResult();
            return Res;
        }
        public static bool IsEmail(string strEmail)
        {
            if (strEmail == null)
                return false;
            Regex rgxEmail = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                       @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                       @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
            return rgxEmail.IsMatch(strEmail);
        }
        [Authorize]
        [HttpPost]
        public ActionResult LoadColumnsByTabName(string TabName)
        {
            return Json(VndGrpRepData.TabColumns[TabName]);
        }
        [Authorize]
        public PartialViewResult AutoComplete(string PropName, string keyword, string TabName)
        {
            RepManager = new ReportManager();
            var data = RepManager.FindKeywordInEntity(PropName, keyword, TabName);
            AutoCompleteViewModel AutoCompVMode = new AutoCompleteViewModel() { Items = data };
            return PartialView("QuotaAutoComplete", AutoCompVMode);
        }
        #region private
        private byte[] ReportGenerator(LocalReport Report, ref MessageBoxViewModel ErrorReport)
        {
            string reportType = "pdf";
            string mimeType;
            string encoding;
            string fileNameExtension;
            //The DeviceInfo settings should be changed based on the reportType            
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx            
            string deviceInfo = "<DeviceInfo>" +
                "  <OutputFormat>jpeg</OutputFormat>" +
                "  <PageWidth>21cm</PageWidth>" +
                "  <PageHeight>29.7cm</PageHeight>" +
                "  <MarginTop>0.5cm</MarginTop>" +
                "  <MarginLeft>1cm</MarginLeft>" +
                "  <MarginRight>1cm</MarginRight>" +
                "  <MarginBottom>0.4cm</MarginBottom>" +
                "</DeviceInfo>";
            Warning[] warnings;
            string[] streams;

            byte[] renderedBytes;
            //Render the report 
            try
            {
                renderedBytes = Report.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
                //Response.AddHeader("content-disposition", "attachment; filename=NorthWindCustomers." + fileNameExtension); 
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
                ErrorReport.Message = ex.Message;
                byte[] error = null;
                return error;
            }

            //  return File(renderedBytes, "pdf");
            var doc = new Document();
            var reader = new PdfReader(renderedBytes);

            using (FileStream fs = new FileStream(Server.MapPath("~/Report/Summary.pdf"), FileMode.Create))
            {
                PdfStamper stamper = new PdfStamper(reader, fs);
                string Printer = "";
                if (Printer == null || Printer == "")
                {
                    stamper.JavaScript = "var pp = getPrintParams();pp.interactive = pp.constants.interactionLevel.automatic;pp.printerName = getPrintParams().printerName;print(pp);\r";
                    stamper.Close();
                }
                else
                {
                    stamper.JavaScript = "var pp = getPrintParams();pp.interactive = pp.constants.interactionLevel.automatic;pp.printerName = " + Printer + ";print(pp);\r";
                    stamper.Close();
                }
            }
            reader.Close();

            FileStream fss = new FileStream(Server.MapPath("~/Report/Summary.pdf"), FileMode.Open);
            byte[] bytes = new byte[fss.Length];
            fss.Read(bytes, 0, Convert.ToInt32(fss.Length));
            fss.Close();
            System.IO.File.Delete(Server.MapPath("~/Report/Summary.pdf"));
            return bytes;
        }

        private byte[] ReportGeneratorExcel(LocalReport Report, ref MessageBoxViewModel ErrorReport)
        {
            string reportType = "Excel";
            string mimeType;
            string encoding;
            string fileNameExtension;
            //The DeviceInfo settings should be changed based on the reportType            
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx            
            string deviceInfo = "<DeviceInfo>" +
                "  <OutputFormat>jpeg</OutputFormat>" +
                "  <PageWidth>21cm</PageWidth>" +
                "  <PageHeight>29.7cm</PageHeight>" +
                "  <MarginTop>0.5cm</MarginTop>" +
                "  <MarginLeft>1cm</MarginLeft>" +
                "  <MarginRight>1cm</MarginRight>" +
                "  <MarginBottom>0.4cm</MarginBottom>" +
                "</DeviceInfo>";
            Warning[] warnings;
            string[] streams;

            byte[] renderedBytes;
            //Render the report 
            try
            {
                renderedBytes = Report.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
                //Response.AddHeader("content-disposition", "attachment; filename=NorthWindCustomers." + fileNameExtension); 
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
                ErrorReport.Message = ex.Message;
                byte[] error = null;
                return error;
            }
            return renderedBytes;
            //  return File(renderedBytes, "pdf");
            var doc = new Document();
            var reader = new PdfReader(renderedBytes);
            using (FileStream fs = new FileStream(Server.MapPath("~/Report/Summary.xlsx"), FileMode.Create))
            {
               
            }
            reader.Close();

            FileStream fss = new FileStream(Server.MapPath("~/Report/Summary.xlsx"), FileMode.Open);
            byte[] bytes = new byte[fss.Length];
            fss.Read(bytes, 0, Convert.ToInt32(fss.Length));
            fss.Close();
            System.IO.File.Delete(Server.MapPath("~/Report/Summary.xlsx"));
            return bytes;
            
        }
        private string DoubleStringGenerator(double? Sum)
        {
            return Sum < 0 ? "(" + Convert.ToDouble(Sum * -1).ToString("C0") + ")" 
                   : Convert.ToDouble(Sum).ToString("C0");
        }
        private string DoubleStringGeneratorF(double? Sum)
        {
            return Sum < 0 ? "(" + Convert.ToDouble(Sum * -1).ToString("C2") + ")"
                   : Convert.ToDouble(Sum).ToString("C2");
        }
        private string FormatPhoneNumber(string phone)
        {
            string phoneNumber = "";
            if (String.IsNullOrEmpty(phone))
                return phone;
            else
                phoneNumber = new String(phone.ToCharArray().Where(c => Char.IsDigit(c)).ToArray());

            Regex phoneParser = null;
            string format = "";

            switch (phoneNumber.Length)
            {

                case 5:
                    phoneParser = new Regex(@"(\d{3})(\d{2})");
                    format = "$1 $2";
                    break;

                case 6:
                    phoneParser = new Regex(@"(\d{2})(\d{2})(\d{2})");
                    format = "$1 $2 $3";
                    break;

                case 7:
                    phoneParser = new Regex(@"(\d{3})(\d{2})(\d{2})");
                    format = "$1 $2 $3";
                    break;

                case 8:
                    phoneParser = new Regex(@"(\d{4})(\d{2})(\d{2})");
                    format = "$1 $2 $3";
                    break;

                case 9:
                    phoneParser = new Regex(@"(\d{4})(\d{3})(\d{2})(\d{2})");
                    format = "$1 $2 $3 $4";
                    break;

                case 10:
                    phoneParser = new Regex(@"(\d{3})(\d{3})(\d{4})");
                    format = "($1) $2-$3";
                    var USPhone = "1-" + phoneParser.Replace(phoneNumber, format);
                    return USPhone;

                case 11:
                    phoneParser = new Regex(@"(\d{1})(\d{3})(\d{3})(\d{4})");
                    format = "$1-($2) $3-$4";
                    break;

                default:
                    return phoneNumber;

            }

            return phoneParser.Replace(phoneNumber, format);

        }
        private MemoryStream GenerateVendorGroup(List<string> allFields, List<string> selectedFields, VendorGroupReportOtherViewModel OtherData, string TabName, string PaperType)
        {
            MemoryStream ms = new MemoryStream();
            VendorGroupReportGenerator gen = new VendorGroupReportGenerator();
            gen.OtherData = OtherData;
            gen.TabName = TabName;
            gen.PaperType = PaperType;
            gen.AllFields = allFields;
            gen.SelectedFields = selectedFields;
            gen.WriteXml(ms);
            ms.Position = 0;
            return ms;
        }


        #endregion
	}


   
}